Tuesday 17 January 2017

Singleton in Threads

Singleton in Threads
From Java 5 onwards volatile variable guarantee can be used to write thread safe singleton by using double checked locking pattern but there are many other simpler alternatives to write thread-safe singleton are available like using static field to initialize Singleton instance or using Enum as Singleton in Java.
     1) Since Enum instances are by default final in Java, it also provides safety against multiple instances due to serialization. One point worth remembering is that, when we talk about thread-safe Singleton, we are talking about thread-safety during instance creation of Singleton class and not when we call any method of Singleton class.
public enum Singleton{
    INSTANCE
;
    public 
void show(){
        System.
out.println("Singleton using Enum in Java");
    
}
}
//You can access this Singleton as Singleton.INSTANCE
Singleton.INSTANCE.show();

    2) You can also create thread safe Singleton in Java by creating Singleton instance during class loading. Static fields are initialized during class loading and Classloader will guarantee that instance will not be visible until it’s fully created. Only disadvantage of using static field is that this is not a lazy initialization and Singleton is initialized even before any clients call there getInstance() method

public class Singleton{
    private static final Singleton INSTANCE = new Singleton
();
 
    private Singleton
(){ }

    public static Singleton getInstance
(){
        return INSTANCE
;
    
}
    public 
void show(){
        System.
out.println("Singleon using static initialization in Java");
    
}
}
//Here is how to access this Singleton class

Singleton.getInstance().show();

No comments:

Post a Comment