Singleton Class - Java

public class Singleton {
    private static Singleton singleton;

    //1. private prevents the instantiation of this object from other clesses
    private Singleton(){
    }

    // 2. static word makes the method class level
    // 3. synchronized avoids the multiple instantiation of object during multiple concurrent calls
    public static synchronized Singleton getSingletonInstance(){
        if(singleton == null){
            singleton = new Singleton();
        }
        return singleton;
    }

    //4. avoiding cloning
    public Object clone() throws CloneNotSupportedException{
        return new CloneNotSupportedException();
    }
}

public class SingletonDemo {

    public static void main(String args[]){
        //Singleton singleton = new Singleton();  //Compilation Error because of private Constructor

        Singleton singleton1 =  Singleton.getSingletonInstance();
        System.out.println("singleton1 hashCode --> "+singleton1.hashCode());

        Singleton singleton2 = Singleton.getSingletonInstance();
        System.out.println("singleton2 hashCode --> "+singleton2.hashCode());

        Singleton singleton3 = Singleton.getSingletonInstance();
        System.out.println("singleton3 hashCode --> "+singleton3.hashCode());
    }
}

Output:
singleton1 hashCode --> 11077203
singleton2 hashCode --> 11077203
singleton3 hashCode --> 11077203


---------------------------------------------------
private static final Object lock = new Object();
private static volatile YourObject instance;

public static YourObject getInstance() {
    YourObject r = instance;
    if (r == null) {
        synchronized (lock) {    // While we were waiting for the lock, another 
            r = instance;        // thread may have instantiated the object.
            if (r == null) {  
                r = new YourObject();
                instance = r;
            }
        }
    }
    return r;
}
This solution ensures that only the first few threads that try to acquire your singleton have to go through the process of acquiring the lock.

----------------------------------------------------------

Efficient way

public enum Foo {
    INSTANCE;
}
Joshua Bloch explained this approach in his Effective Java Reloaded talk at Google I/O 2008: link to video. Also see slides 30-32 of his presentation (effective_java_reloaded.pdf):

The Right Way to Implement a Serializable Singleton

public enum Elvis {
    INSTANCE;
    private final String[] favoriteSongs =
        { "Hound Dog", "Heartbreak Hotel" };
    public void printFavorites() {
        System.out.println(Arrays.toString(favoriteSongs));
    }
}
"This approach is functionally equivalent to the public field approach, 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. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton."

Comments

Popular posts from this blog

public vs protected vs default access modifiers - Java

Class, Reference and Object