我创建了自己的简单、紧凑的 ReadWriteLock 实现。第一个在尝试获取读锁时使用自旋锁。如果设置了锁定位,则第二个通过在旋转之前暂时获取写锁来避免自旋锁。这样,它会停止执行,直到写锁被释放。现在我的问题是哪个更有效,更适合常用?(多核和非多核机器)
编辑:它将用于我的 Android 应用程序。所以我必须在提供我需要的 ReadWriteLock 实现的同时保持它的紧凑性。ReentrantReadWriteLock 对我的应用程序来说很重。另外,有人可以提出更好的方法吗?
编辑:实施细节取自此链接。
第一个实现如下:
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
public class SpinSeqLock {
private AtomicLong status = new AtomicLong();
private ReentrantLock writeLock = new ReentrantLock();
public long readLock() {
long current;
do
current = status.get();
while ((current & 1) != 0);
return current;
}
public boolean tryReadUnlock(long previous) {
return status.get() == previous;
}
public void writeLock() {
writeLock.lock();
status.incrementAndGet();
}
public void writeUnlock() {
status.incrementAndGet();
writeLock.unlock();
}
public void writeLockInterruptibly() throws InterruptedException {
writeLock.lockInterruptibly(); // If we get interrupted, do not proceed below!
// Increment only on successful uninterrupted lock
status.incrementAndGet();
}
}
第二种实现如下:
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantLock;
public class SemiSeqLock {
private AtomicLong status = new AtomicLong();
private ReentrantLock writeLock = new ReentrantLock();
public long readLock() {
for (;;) {
long current = status.get();
if ((current & 1) == 0)
return current;
writeLock.lock(); // Avoids spin lock by halting until lock-acquisition.
writeLock.unlock();
}
}
... // Same code as the first one
}
预期的用法是:
读者话题:
for (;;) {
final long status = seqLock.readLock();
// ... some read operation ...
// ... some read operation ...
if (seqLock.tryReadUnlock(status)) break;
}
作家主题:
seqLock.writeLock();
try {
// ... some write operation ...
// ... some write operation ...
} finally {
seqLock.writeUnlock();
}
有什么更正吗?哪一个更好?