How to implement the singleton pattern in Java

This example shows how to implement the Singleton pattern in Java. This is valid from Java 5 and up.
The constructor of the class needs to be private, so it can not be invoked outside of the class. The variable holding the instance referencing the singleton needs to be static volatile, so it's not cached when several threads are accessing it during the initialization. The method returning the singleton is static and uses a double test to see if the instance is null, one without synchronization and if it fails it is redone with synchronization.
This ensures that when the instance is loaded we have faster performance and when 2 threads try to load the singleton at the same time, only one loads it.

Create the following java file:

public class Singleton {

	// The instance of the singleton
	private static volatile Singleton instance = null;

	// private constuctor so it's not accessed outside the class
	private Singleton() {
	 * The method used to access the instance
	 * @return
	public static Singleton getInstance(){
		// Test if the instance exists
		if( instance == null ){
			// synchronize on the class Object
			synchronized( Singleton.class ){
				// Test if the instance exists
				if( instance == null ){
					// Create the instance
					instance = new Singleton();
		// Return the instance
		return instance;
	public static void main(String[] argv){
		Singleton singleton = Singleton.getInstance();


Java 8

Recent Comments