Creational Patterns  «Prev 

Singleton Pattern in Java

Singleton Variations

Use the Singleton1 form when you cannot create the object at class-load time (for example, you did not have information determined by program state or is passed to the creation method). You must synchronize the instance() method of Singleton1 as shown.

Use the Singleton2 or Singleton3 form when possible; synchronization is not required during access.
(The JVM may load the class at any time, but it should not initialize the Class object until first use )c
Java Language Specification, 12.4 static initializers should not execute until first use.c
Call addShutdownHook() in the constructor when program-shut-down cleanup activities (such as shutting down database connections in an orderly way) are required.
Do not use a finalizer, which may never be called. A private constructor prevents someone from saying new Singleton(), thereby forcing access through instance().
You have no requirement that only one instance of the Singleton exists, only that the number of instances are constrained and that access to the instances are global. For example, a

DatabaseConnection.getInstance() 
method may return one of a pool of database connections that the Singleton manages.
In UML, the role associated with the Singleton is usually also the class name.

Singleton1

Class Singleton1{ 
	private static Singleton instance;
	private Singleton1(){ 
		Runtime.getRuntime().addShutdownHook(new Thread(){ 
			public void run(){ 
			/* clean-up code here */
			}
		});
	}
	public static synchronized Singleton instance(){ 
		if( instance == null )
			instance = new Singleton();
		return instance;
	}
}

Singleton2

package com.gofpatterns.creational.singleton;
class Singleton2{ 
	private static final Singleton instance=new Singleton2();
	public static Singleton instance(){ 
		return instance;
	}
	/*Other than creating object in static
	initializer, is identical to Singleton1*/
}

Singleton3

package com.gofpatterns.creational.singleton;
class Singleton3{ 
	static Type allFields;
	static Type allOperations();
	/* No instance() method, just use the
	class name to the left of the dot. */
}