How to create singleton class in Java?

How To Create Singleton Class In Java?

A Singleton class is a class that can have only one object (an instance of the class) at a time. Singletons typically represent either a stateless object such as a function (Item 24) or a system component that is intrinsically unique. 

How to create Singleton classes?

There are two ways which we will discuss in this article. 

The basic principle to create a singleton class is- ‘Make constructor private and exporting a public static member to provide access to the sole instance’.

Now there can be 2 approaches for this

Use public final field for Singleton Implementation

// Singleton with public final field 
public class Elvis 
public static final Elvis INSTANCE = new Elvis(); 
private Elvis() { ... } 
public void leaveTheBuilding() { ... } 

The private constructor is called only once, to initialize the public static final field Elvis

The lack of a public or protected constructor guarantees that exactly one instance will exist once the class is initialized.

It seems the perfect design and it’s not directly possible to create a second instance for the class as there is no constructor to call directly.

But someone can sure call its private constructor using reflection by calling AccessibleObject.setAccessible method. 

To defend against this, modify the constructor to make it throw an exception if it’s asked to create a second instance.

Advantage: The main advantage of using this approach is that it is simpler to use, API is much clearer and one can guess that class is a singleton: The public static field is final, so it will always contain the same object reference.

public member is a static factory method:

// Singleton with static factory 
public class Elvis { 
private static final Elvis INSTANCE = new Elvis(); private Elvis() { ... } 
public static Elvis getInstance() 
     return INSTANCE; 
public void leaveTheBuilding() { ... } }

All calls to Elvis.getInstance return the same object reference, and no other Elvis instance will ever be created. 

But calling private constructor can still work in this approach so the same solution should be applied in this approach also.

Advantage: of static factory approach: it gives you the flexibility

to change your mind about whether the class is a singleton without changing its

API. The factory method returns the sole instance, but it could be modified to

return, say, a separate instance for each thread that invokes it.

How to make Singleton classes Serializable?

To maintain the singleton guarantee, declare all instance fields transient and provide a readResolve method

For Serializable and Externalizable classes, the readResolve method allows a class to replace/resolve the object read from the stream before it is returned to the caller. By implementing the readResolve method, a class can directly control the types and instances of its own instances being deserialized.

The readResolve method is called when ObjectInputStream has read an object from the stream and is preparing to return it to the caller. ObjectInputStream checks whether the class of the object defines the readResolve method. If the method is defined, the readResolve method is called to allow the object in the stream to designate the object to be returned. The object returned should be of a type that is compatible with all uses. If it is not compatible, a ClassCastException will be thrown when the type mismatch is discovered.

Or else when serialized instance of the class will be deserialized, a new instance for it will be created, which breaks the concept of being a Singlton class.

// readResolve method to preserve singleton property 

private Object readResolve() 
// Return the one true Elvis and let the garbage collector // take care of the Elvis impersonator. 
return INSTANCE; 

The disadvantage of making your class singleton?

singleton can make it difficult to test its clients because it’s impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type

Related posts

Intro to static factory methods and when should you prefer static methods over Constructors?


Static factory vs Factory pattern


Introduction to JVM and its internals

Leave a Reply

Your email address will not be published. Required fields are marked *

Join The Club!

Be the first to learn about
our amazing Articles

let's Learn together