double locked Singleton

How to write double locked Singleton class in Java ?

we can check double locked in java singleton class as below code

public class SingletonInstanceDemo {
    private static volatile SingletonInstanceDemo instance = null;
    // private constructor
    private SingletonInstanceDemo() {
    }
    public static SingletonInstanceDemo getInstance() {
        if (instance == null) {
            synchronized (SingletonInstanceDemo.class) {
                // Double check
                if (instance == null) {
                    instance = new SingletonInstanceDemo ();
                }
            }
        }
        return instance;
    }
}

No comments:

Post a Comment