Singleton Design Pattern VS Spring Singleton Scope

  • First off, the Singleton design pattern is.. well.. a design pattern whereas Spring’s singleton refers to the singleton scope which by the way is the default bean scope in Spring.
  • The Singleton design pattern is effectively a unique instance of an object per class loader whereas Spring singleton scope ensures the presence of a unique bean per application context.
  • Spring’s singleton scope is uniquely identified by the bean’s id meaning that we can have several beans of the same class type with different ids.
  • Spring’s singleton scoped bean is nothing more than a reference to an object, which, once instantiated, it gets cached by the IoC container and provided upon request. So in short the Spring container that deals with the beans lifecycle is handling internally the bean references and make a reference look like a singleton design pattern-ed object although it’s not.
  • We can have a situation where we inject a prototype-scoped bean into a singleton-scoped bean. That would mean, every time we are requesting the singleton-scoped bean a new object will be injected as a dependency for the prototyped-scoped dependency.

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.