Thread safe Singleton with double checked locking

suggest change

This type of Singleton is thread safe, and prevents unnecessary locking after the Singleton instance has been created.

public class MySingleton {

    // instance of class
    private static volatile MySingleton instance = null;

    // Private constructor
    private MySingleton() {
        // Some code for constructing object
    }

    public static MySingleton getInstance() {
        MySingleton result = instance;
        
        //If the instance already exists, no locking is necessary
        if(result == null) {
            //The singleton instance doesn't exist, lock and check again
            synchronized(MySingleton.class) {
                result = instance;
                if(result == null) {
                    instance = result = new MySingleton();
                }
            }
        }
        return result;
    }
}

It must be emphasized – in versions prior to Java SE 5, the implementation above is incorrect and should be avoided. It is not possible to implement double-checked locking correctly in Java prior to Java 5.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents