Java Language Thread safe Singleton with double checked locking


Example

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

Java SE 5
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.