我尝试使用非阻塞原子布尔 API 来生成单例对象而不是同步对象。
我有 2 个实现
- 通过双重锁定和同步关键字
- 通过原子非阻塞调用
我相信我们可以通过 Atomic 实现比同步更强大和更好的实现。请建议我是否不正确。还执行一些基本的性能测试,这些测试有利于原子实现而不是同步。
支持
// 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;
}
}
更新@Kayaman 正确识别出上述 impl 不是线程安全的。我固定在下面的一个。
// 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;
}