The Correct way of Singleton Implementation

The following implementation of Singleton design pattern will handle most of the flaws we made till now.

/**
* Hard-to-get-it-right implementation of a Singleton supporting lazy
* instantiation.
*/
public class Singleton implements Cloneable {
private static final long serialVersionUID = 6462568326558031828L;

/*
* Marking volatile is necessary for avoiding the threads from creating
* their own copies, even with double checked locking.
*/
private static volatile Singleton INSTANCE = null;

/*
* Guard against 'reflection' to create a new instance.
*/
private Singleton() {
if (INSTANCE != null) {
throw new IllegalStateException();
}
}

/*
* Synchronizes only on the critical section, and uses double checked
* locking to ensure that all get requests are not Synchronized once the
* instance is created.
*/
public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized (Singleton.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}

/**
* Yeah, why dont you try cloning me?
*/
@Override
protected Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();

}
}

core java 12 Creational-Pattern 12

FOLLOW US ON LinkedIn



Explore Tutu'rself