有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓 java自己的SeqLock实现,避免spinlock会更好吗?

我创建了自己的简单、紧凑的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();
}

有什么更正吗?哪一个更好


共 (0) 个答案