您是说您希望所有其他九个线程都运行而无需一次获得一个锁。
首先,我不得不提一下,等待初始化后获取锁的性能问题很小。其次,单例是邪恶的,有更好的方法来实现它们。
但是,如果您想部分地重新实现锁,那么您可以这样做。这样做可能有一些现成的Future
,但我什么都看不到。无论如何,糟糕的实施让我一头雾水:
private static final AtomicReference<Object> ref = new AtomicReference<>();
// <Object> as we require two distinguished values. :(
// (I guess could use a mark.)
public static Singleton getInstance() {
for (;;) { // May want to play with park to avoid spinning.
Object obj = ref.get();
if (obj instanceof Singleton) {
return (Singleton)obj;
}
if (ref.weakCompareAndSet(null, Thread.currentThread())) {
Singleton instance = null; // To reset on fail.
try {
instance = new Singleton();
} finally {
ref.set(instance);
}
return instance;
}
}
}
我想我们可以在不变得太复杂的情况下做得更好,再次假设没有例外:
{
Object obj = ref.get();
if (obj instanceof Singleton) {
return (Singleton)obj;
}
}
if (ref.compareAndSet(null, Thread.currentThread())) {
Singleton instance = new Singleton();
ref.set(instance);
return instance;
}
for (;;) {
Object obj = ref.get();
if (obj instanceof Singleton) {
return (Singleton)obj;
}
}