I have tried to utilized Non Blocking Atomic Boolean API to generate singleton object instead of synchronized.
I have 2 implementations
- Via Double Locking and Synchronized Keyword
- Via Atomic Non Blocking Call
I believe we can have robust and better implementation via Atomic than synchronized. Please suggest if i am incorrect. Also performs some basic test for performance which favors Atomic implementation over synchronized.
Supports
// Lazy Initialization
// Thread-safe
// Performance improvement for corresponding calls, once the object is created
public class Singleton {
private static Singleton instance;
static final AtomicBoolean isInitialized = new AtomicBoolean(false);
private Singleton() {
// private constructor //Thread.sleep(10)
}
// 1st Implementation
// Via Double Locking and Synchronized
public static Singleton getInstance() {
if (instance == null) {
// synchronized block to remove overhead
synchronized (Singleton.class) {
if (instance == null) {
// if instance is null, initialize
instance = new Singleton();
}
}
}
return instance;
}
// 2nd Implementation + Not ThreadSafe with Null Objects.
// Via Atomic Non Blocking Method and avoiding Synchronized
public static Singleton getInstanceViaAtomic() {
if (instance != null)
return instance;
if (isInitialized.compareAndSet(false, true)) {
return instance = new Singleton();
}
return instance;
}
}
Update @Kayaman correctly identified the above impl was not threadsafe. I fixed in the below one.
// 2nd Implementation + Thread Safe
// Via Atomic Non Blocking Method and avoiding Synchronized
public static Singleton getInstanceViaAtomic() throws InterruptedException {
while(instance == null) {
if (isInitialized.compareAndSet(false, true)) {
instance = new Singleton();
}
}
return instance;
}