Wednesday, April 22, 2015

Singlton in Java

Singlton in Java


Definition: Single instance for application or per session. Singleton classes represent objects for which only one single instance should exist for application or session.
Before making Singlton: Ask yourself "Is there important to make this class as Singlton or will any actual harm come to the system". If the answer is no, so no need to create it. If the answer is yes, you can create it.
There are so many ways to create it.
1) First Approach: The public member variable is static final field.


public class SingletonObject{
   public static final SingletonObject INSTANCE = new SingletonObject();
   private SingletonObject(){
          //...
   }
  public void doSomeWorkForUs(){
  //...
 }
}

  The private constructor is called only once, to initialize the public static final field SingletonObject .INSTANCE. Exactly one SingletonObject instance will exist once the SingletonObject class is initialized—no more, no less. Instance is created irrespective of it is required in runtime or not. If this instance is not big object and you can live with it being unused, this is best approach.

 2) Second Approach: The Public member is static factory method


public class SingletonObject{
    private static final SingletonObject INSTANCE = new SingletonObject();
    private SingletonObject(){ //..
    }
    public SingletonObject getInstance(){ 
        return INSTANCE;
   }
    public void doSomeWorkForUs(){
   //...
  }
}

All calls to SingletonObject .getInstance return the same object reference, and no other SingletonObject instance will ever be created. This is same as above approach. Instance is created irrespective of it is required in runtime or not. If this instance is not big object and you can live with it being unused, this is best approach.



3) Third Approach: Considering the thread safety


public class SingletonObject{
     private static volatile SingletonObject INSTANCE = null;
     private SingletonObject(){ //..
     }
     //Double null check, incase multiple threads are accessing at a time this method.
     public SingletonObject getInstance(){
         if(null !=instance){
                synchronized (SingletonObject.class){
                     if(null !=instance){
                                INSTANCE = new SingletonObject();
                     }
}
         }
         return INSTANCE;
    } 
    public void doSomeWorkForUs(){
     //...
     }
}
 The performance reason we are using "synchronized" block. And here we are checking null condition on the INSTANCE two times. First thread checks first null condition and it holds the class object. And still not created the INSTANCE. At this time one more thread enters into this method and checks the first null condition it is true and waits for the lock on this class object. And first thread creates the INSTANCE and release the lock. Then 2nd thread holds the object lock and checks the 2nd null condition, at this time already INSTANCE is created so it will not create one more INSTANCE object. Then next time onwards, first null condition itself fails and returns INSTANCE.

4) Fourth Approach: Enum type with one element.


public enum SingletonObject{
     INSTANCE
     public void doSomeWorkForUs(){
     //...
    }
}

This approach is functionally equivalent to the first approach (public field), except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. A single-element enum type is the best way to implement a singleton.

The Singleton design pattern addresses all of these concerns. With the Singleton design pattern you can:
  • Ensure that only one instance of a class is created
  • Provide a global point of access to the object
  • Allow multiple instances in the future without affecting a singleton class's clients

Example for the Singleton patterns in practical examples:
1) Logging
2) Calender
3) Device Drive Objects
4) Thread pools
5) Configuration settings.


 Please provide your inputs or comments or suggestions to make it better.

No comments:

Post a Comment