要执行无锁和无等待延迟初始化,我执行以下操作:
private AtomicReference<Foo> instance = new AtomicReference<>(null);
public Foo getInstance() {
Foo foo = instance.get();
if (foo == null) {
foo = new Foo(); // create and initialize actual instance
if (instance.compareAndSet(null, foo)) // CAS succeeded
return foo;
else // CAS failed: other thread set an object
return instance.get();
} else {
return foo;
}
}
它工作得很好,除了一件事:如果两个线程看到 instance null
,它们都会创建一个新对象,只有一个幸运的是通过 CAS 操作设置它,这会导致资源浪费。
有没有人建议另一种无锁延迟初始化模式,它降低了两个并发线程创建两个昂贵对象的可能性?