Java Singleton Design Pattern Example

Eagerly created singleton non-multithreaded version:

public class Singleton {

	public static Singleton singleton = new Singleton();
	
	private Singleton(){}
}

In the above example it is evident that the public static field is exposing the singleton upon creation. The constructor is of course private and concealed from the outer world.

Eagerly created singleton multithreaded version:

public class Singleton {

	public static volatile Singleton singleton = new Singleton();
	
	private Singleton(){}
}

The only addition in the above code is the volatile identifier that is forcing all threads that request read to this variable to cross the memory barrier to the main memory and not rely on JVM registry and cache-local optimisations.

Lazily created singleton multithreaded version:

public class Singleton {

	private static volatile Singleton singleton;
	
	private Singleton(){}
	
	public static Singleton getSingleton(){
		if(singleton==null)
			singleton = new Singleton();
		return singleton;
	}
}

In the above example note that the static field has been changed to private scope so only accessible from inside the object. Also the field is set to null by default postponing the instantiation when the singleton is first needed. Moreover, it has been added a factory method lazily instantiates the singleton.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s