Feeds:
Posts
Comments

Archive for the ‘Technology’ Category

http://www.java-samples.com/showtutorial.php?tutorialid=812

Read Full Post »

The Spring is

  • light weight,
  • non-invasive IoC Container and AOP framework.
  • It provides support for JPA, Hibernate, Web services, Schedulers, Ajax, Struts, JSF and many other frameworks
  • The Spring MVC components can be used to developed MVC based web applications.

http://bazlur12.wordpress.com/2010/11/27/web-programming-with-java-spring-framework-part-1/

– This link is used to learn new to spring technology work.

Read Full Post »

 Double-check locking Mechanism

                   We looked into a thread safe mechanism to create singleton
objects.The concept works well enough for most systems. However, when this becomes a hot section (heavily accessed) in your code, we will begin to hit performance problems. Here’s why: Lets say we have a high performant system,with 50-100 threads working around like magic, sharing tasks and running as fast as possible. Lets say that all the threads hit this hot section very often. This will result in the hot section being a real bottle neck, synchronizing and slowing down all the threads. Every thread enters this critical section and blocks every other thread from using this section. But is this really required? The ‘clever’ double locking system ‘tries’ to fix this problem.

Instead of locking down the critical section and blocking all the threads, this technique gives a chance for the threads to synchronously
check, whether or not it needs to enter this section in the first place. If it does (when instance != null), it then locks the section and proceeds in a normal thread safe manner where it does the second check. So the name, Double Checked Locking.

public class Singleton {

    // volatile is needed so that multiple threads can
    // reconcile the instance
    // semantics for volatile changed in Java 5.
    private volatile static Singleton singleton;

    private Singleton() {

    }

    // synchronized keyword has been removed from here
    public static Singleton getSingleton() {
        // needed because once there is singleton

        // available no need to acquire
        // monitor again & again as it is costly
        if(singleton==null) {
            synchronized(Singleton.class){
            // this is needed if two threads are waiting at the monitor

           // at the time when singleton was getting instantiated
                if(singleton == null) {
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
    ..
    ..
    ..
    public void whatever(..){

    }
}

Refer more on below links… http://www.ibm.com/developerworks/java/library/j-dcl.html

Read Full Post »

Initialization On Demand Holder( IODH)  

                                                  The Singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a Singleton does not yet exist, they both must check for an instance of the Singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation.

One way


public final class Singleton {

  // Private constructor suppresses generation
  // of a (public) default constructor.

  private Singleton() {

  }

  private static class SingletonHolder {
     private static Singleton uniqueInstance= new Singleton();
  }

  public static final Singleton getInstance() {
     return SingletonHolder.uniqueInstance;
  }

  ...
  ...
  ...
  public void whatever(..){

  }
}

Hints

  • Basicaly, Java Language Specification (JLS) guarantees that instance would not be initialized until someone calls getInstance() method.
  • Lazy instantiation.
  • No synchrronized (performance intensive) method used.
  • Lack of any public actors (only the getInstance method is made public) makes it impossible to subclass this class in non thread safe manner.
  • Making it final speak it better.

Second way

public final class Singleton{

    private static final Singleton uniqueInstance= new Singleton();

    private Singleton() {

    }

    public static finalSingleton getInstance() {
        returnuniqueInstance;
    }
   ...
    ...
    ...
    public void whatever(..){

    }
 }

Hints

  • No lazy instantiation.
  • Sufficient for allmost all the cases.?

Third way

public final class Singleton {

   private static final Singleton uniqueInstance;

   private Singleton() {

   }

   public static final synchronizedSingleton getInstance() {
     if(uniqueInstance== null) {
              uniqueInstance= new Singleton();
      }
     returnuniqueInstance;
   }
    ...
    ...
    ...
    public void whatever(..){

    }

}

Hints

  • The problem with this solution is that synchronized method getInstance() is called every time, while synchronization is actually needed only for the first call of the method (which introduces performance overhead in your application).
  • Therefore this implementation is not prefered in most cases due to performance concern.

Comments

  • Since synchronizing a method can decrease performance by a factor of 100 or higher.
  • The overhead of acquiring and releasing a lock every time this method.
  • Once the initialization has been completed, acquiring and releasing the locks would appear unnecessary.
  • Better we can go for Double-check locking Mechanism.

Read Full Post »

1. Lazy initialization

Lazy initialization

Make the class of the single instance object responsible for creation, initialization, access, and enforcement. Declare the instance as a private static data member. Provide a public static member function that encapsulates all initialization code, and provides access to the instance.

public class Singleton {

    private static final Singleton _instance = new Singleton();

    private Singleton() {

    }

    public static Singleton getInstance() {
        return _instance;
    }
    ..
    ..
    ..
    public void whatever(..){

    }
}

Comments

  • When JVM start loading all classes by Class Loader, then this class loaded and by default this Singleton Object also created and put into heap. If your work flow not using this class, then its waste of having all time in heap memory.
  • Singleton with lazy initialization but not thread-safe.
  • Better we can go for on-Demand case.

Read Full Post »

6.Enum Singleton

Enum Singleton  

                              A more effective approach to implementing singletons since  J2SE 1.5,  is  with  an  enum type containing only one element. Recently I’ve been going through some effective technics to implement popular design patterns and I was surprised to see how few people where aware of them.  For example since Java 5 the best way to implement the Singleton pattern is simply to use an enum. Unlike Classes, an Enum has fix number of objects and since this restriction is implemented by JVM’s native libraries, hence it is unbreakable.

 

Let’s see an example:

// Enum singleton - the preferred approach
public enum EnumSingleton {
  _instance;  
  public void whateverMethod() { ... }
}

Now let’s try to create an object of EnumSingleton using reflection:

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
 public class enumTest {
  public static void main(String[] args) throws ClassNotFoundException,
   IllegalArgumentException, SecurityException,
   InstantiationException, IllegalAccessException,
   InvocationTargetException {  
   Constructor c1 = Class.forName("EnumSingleton").getDeclaredConstructors()[0];
   c1.setAccessible(true);
   EnumSingleton e1 = (EnumSingleton) c1.newInstance(null);
  }
}

 

Output:

 Exception in thread “main” java.lang.IllegalArgumentException: 
 Cannot reflectively create enum objects

  at java.lang.reflect.Constructor.newInstance(Constructor.java:511)
  at enumTest.main(enumTest.java:11)

Comments

  • Hence, we can conclude that best way to implement a Singleton pattern is by using Enum.
  • It is simple, straightforward and unbreakable.
  • If you allow reflection, you can always break
    java assumptions.
  • If your code is meant to protected from one kind of reflection only, it is meaningless.

Refer more on below links…

 http://ctotodevelopers.blogspot.com/2007/01/java-practice-when-not-to-use-enums.html

Read Full Post »

Reflection:: Hack any Java class

                                     Ever  wondered  what  evil  power can  be unleashed when  using  reflection?  Do you  think  private  methods are really only accessible from within the declaring class? Do you think that a private field can only be modified from within the declaring class? No? That’s what I thought!! In this blog, I will try to demonstrate that it is always important to correctly set the security properties of your applications. For instance, let’s look at the following example where we successfully retrieve a private password from another class.

 class A {
    private static String getPassword() {
      return "someHighlyPreciousPassword";
    }
  } 
public class Test {
  public static void main(String[] args) throws Exception {
    Class cl = Class.forName("A");
    java.lang.reflect.Method[] m = cl.getDeclaredMethods();
    m[0].setAccessible(true);
    String password = (String) m[0].invoke(null, null);
    System.out.println("I got it:" + password);
  }
}

Output :

I got it :  someHighlyPreciousPassword

Let’s take an real singleton example. Let’s mess up a class that implements the Singleton pattern. In the normal case, a singleton object is supposed to be the only instance of a given class. To achieve this, we usually declare the class constructor private, so that no one can invoke it. Well, as demonstrated below, with reflection we can bypass this restriction and create a second “singleton object”.

Class        ::    Generic Singleton class
Class Test   ::    Class trying to Hack – One way
 

class A {
    public static final A singleton = new A("I'm the only instance of class A");
    private String name;
    private A(String name) {
      this.name = name;
    }
    public String toString() {
      return this.name;
    }
  } 
public class Test {
    public static void main(String[] args) throws Exception {
      Class cl = Class.forName("A");
      java.lang.reflect.Constructor[] c = cl.getDeclaredConstructors();
      c[0].setAccessible(true);
      A anotherA  = (A) c[0].newInstance(new Object[]{"Not anymore!!"});
      System.out.println(A.singleton);
      System.out.println(anotherA);
    }
  }

Output:
 I’m the only instance of class A
 Not anymore!!

Using this technique, you can create an instance of any non-abstract class,even if all its constructors are declared private.

  • For instance, below we create an instance of the Math class even though it is useless since the Math class has no instance method. Still,it is possible to do it.

Class Test  ::  Class trying to Hack – Second way

 public class Test {  
  public static void main(String[] args) throws Exception {
       Class cl = Class.forName("java.lang.Math");
       java.lang.reflect.Constructor[] c = cl.getDeclaredConstructors();
       c[0].setAccessible(true);
       Math mathInstance = (Math) c[0].newInstance(null);
       System.out.println(mathInstance);
        }  
 }

 

Class Test ::  Class trying to Hack – Third way

 public class Test {
  public static void main(String[] args) throws Exception {
     Class clazz = java.lang.Math.class;
     Constructor cons = clazz.getDeclaredConstructor();
     cons.setAccessible(true);
     Math mathInstance =(Math) cons.newInstance();
     System.out.println(mathInstance);
    }
  }

 

  • Finally, let’s mess with the Runtime class which has one private static fieldfor storing the current Runtime instance.
  • This is another example of a badly implemented singleton class. Let’s look at the code below.
  • We first retrieve the current runtime object and display it (3-4). Then, we set the Runtime.currentRuntime static field to null, which means that all successive calls to Runtime.getRuntime() will yield null (6-9) since currentRuntime is initialized at class loading time.
  • We then get the currentRuntime field again and display its value (11-12). finally, we try to use the current runtime to execute a cmd for displaying the content of the current directory (14).
    The output talks for itself.
 
 public class Test { 
    public static void main(String[] args) throws Exception {
        Runtime r = Runtime.getRuntime();
        System.out.println("Before: Runtime.getRuntime() yields " + r);
        Class cl = Class.forName("java.lang.Runtime"); 
        java.lang.reflect.Field f = cl.getDeclaredField("currentRuntime");
        f.setAccessible(true);
        f.set(null, null);  
        r = Runtime.getRuntime();   
        System.out.println("After: Runtime.getRuntime() yields " + r); 
        r.exec("dir"); //raises NullPointerException!!
   }
 }

 Output:

 Before: Runtime.getRuntime() yields java.lang.Runtime@cac268
 After: Runtime.getRuntime() yields null
 Exception in thread “main” java.lang.NullPointerException
                                                        at Test.main(Test.java:59)

  • All this could have been avoided if the currentRuntime field had been  declared final.
  • Nothing prevents setAccessible(true) to be called on the field (8)
  • But when the set(null, null) method is called, llegalAccessException is thrown with the message “Field is final”.

Another way of Protect from Hacker’s

 
public class Test {  
 public static void main(String[] args) throws Exception {
   //To protect from Reflection    
   SecurityManager mgr = new SecurityManager();    
   System.setSecurityManager(mgr);         
   Class clazz = java.lang.Math.class;    
   Constructor cons = clazz.getDeclaredConstructor(); 
   cons.setAccessible(true);    
   Math mathInstance =(Math) cons.newInstance();
   System.out.println(mathInstance);   
 } 
 }

 

Output:
Exception in thread “main” java.security.AccessControlException:
Access denied (java.lang.reflect.ReflectPermission suppressAccessChecks)
 at java.security.AccessController.checkPermission(AccessController.java:108)
 at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
 at java.lang.reflect.AccessibleObject.setAccessible(AccessibleObject.java:118)
 at com.paypal.source.SingletonTester.main(SingletonTester.java:94)

Read Full Post »

Older Posts »