Java Language Singletons Thread safe Singleton with double checked locking

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any Java Language Question?