我创建了自己的简单、紧凑的 ReadWriteLock 实现。第一个在尝试获取读锁时使用自旋锁。如果设置了锁定位,则第二个通过在自旋之前暂时获取写锁来避免自旋锁。这样,它会停止执行,直到写锁被释放。现在我的问题是哪个更高效,更适合常用? (多核和非多核机器)
编辑:它将用于我的 Android 应用程序。所以我必须在提供我需要的 ReadWriteLock 实现的同时保持它的紧凑。 ReentrantReadWriteLock 对我的应用程序来说很重。另外,谁能推荐更好的方法?
编辑:实现细节取自this link .
第一次实现如下:
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();
}
任何更正?哪个更好?
最佳答案
你确定吗
- 你需要它并且
- 您可以让它比现有实现更好吗?
这样的事情很容易出错,比通常的程序要多得多。
所以真的真的尝试使用现有的锁。
你的锁至少有一个错误:writeLockInterruptibly
必须使用 finally
。
在性能方面,通过 writeLock
长时间 sleep 之前旋转几次可能是明智的。总的来说,我不确定它是否有效...但它看起来很有趣。
再一次:首先尝试一些由在该领域非常聪明且经验丰富的人编写的现有锁。
关于java - 自己的 SeqLock 实现,避免自旋锁会更好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19577909/