我写了一个Java ReadWriteLock,读者使用双重检查锁定来获取写锁。这是不安全的(就像带有惰性实例化的 DCL 的情况一样)?
import java.util.concurrent.atomic.AtomicInteger;
public class DCLRWLock {
private boolean readerAcquiringWriteLock = false;
private boolean writerLock = false;
private AtomicInteger numReaders = new AtomicInteger();
public void readerAcquire() throws InterruptedException {
while (!nzAndIncrement(numReaders)) {
synchronized (this) {
if (numReaders.get() != 0)
continue;
if (readerAcquiringWriteLock) {
do {
wait();
} while (readerAcquiringWriteLock);
} else {
readerAcquiringWriteLock = true;
writerAcquire();
readerAcquiringWriteLock = false;
assert numReaders.get() == 0;
numReaders.set(1);
notifyAll();
break;
}
}
}
}
public void readerRelease() {
if (numReaders.decrementAndGet() == 0)
writerRelease();
}
public synchronized void writerAcquire() throws InterruptedException {
while (writerLock)
wait();
writerLock = true;
}
public synchronized void writerRelease() {
writerLock = false;
notifyAll();
}
// Atomically:
// If x is nonzero, increments x and returns true
// Otherwise returns false
private static boolean nzAndIncrement(AtomicInteger x) {
for (;;) {
int val = x.get();
if (val == 0)
return false;
else if (x.compareAndSet(val, val + 1))
return true;
}
}
}
我知道 Java 已经有了 ReentrantReadWriteLock。我对如何确定哪种形式的 DCL 安全或不安全的一般问题更感兴趣?