是否有带有 java 侦听器的读写锁?

Dan*_*rry 5 java concurrency java-8

是否有一个 Java 库实现了一些行为类似于 aReadWriteLock但使用侦听器或 CompletableFuture/CompletionStage 而不是阻塞的东西?

理想情况下,我想写:

lock = ...

CompletionStage stage = lock.lockRead();
stage.thenAccept(r -> { doSomething(); r.release(); });
Run Code Online (Sandbox Code Playgroud)

同样重要的是:

CompletionStage stage = lock.tryLockWrite(10, TimeUnit.SECONDS);
stage.handle(callback);
Run Code Online (Sandbox Code Playgroud)

我想知道这样的东西是否存在,如果它存在,它是如何调用的

我不打算自己实现这个,而是使用一个库来简化一些框架代码。

Slu*_*ler 2

我认为自己写应该还不够难。很可能比寻找图书馆花费的时间更少。总体来说非常简单:

static const int STATE_UNLOCKED = 0;
static const int STATE_READING = 1;
static const int STATE_WRITING = 2;
int state = STATE_UNLOCKED;
int readers = 0;
Queue<CompletableFuture<Void>> queueWriters = new LinkedList<CompletableFuture<Void>>();
Queue<CompletableFuture<Void>> queueReaders = new LinkedList<CompletableFuture<Void>>();

public synchronized CompletionStage<Void> lockWriter() {
    CompletableFuture<Void> l = new CompletableFuture<Void>();
    if (state == STATE_UNLOCKED) {
        state = STATE_WRITING;
        l.complete(null);
        return l;
    }
    queueWriters.offer(l);
    return l;
}

public synchronized CompletionStage<Void> lockReader() {
    CompletableFuture<Void> l = new CompletableFuture<Void>();
    if (state != STATE_WRITING) {
        state = STATE_READING;
        readers++;
        l.complete(null);
        return l;
    }
    queueReaders.offer(l);
    return l;
}

public void unlock() {
    CompletableFuture<Void> l = null;
    synchronized(this) {
        if (state == STATE_READING) {
            readers--;
            if (readers > 0) {
                return;
            }
        }
        l = queueReaders.poll();
        if (l != null) {
            state = STATE_READING;
            readers++;
        }
        else {
            l = queueWriters.poll();
            if (l != null) {
                state = STATE_WRITING;
            }
            else {
                state = STATE_UNLOCKED;
                return;
            }
        }
    }
    l.complete(null);
    while (true) {
        synchronized (this) {
            if (state != STATE_READING) {
                return;
            }
            l = queueReaders.poll();
            if (l == null) {
                return;
            }
            readers++;
        }
        l.complete(null);
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面添加定时锁定(通过使用某种“过期队列”或编写器饥饿预防(如果queueWriters不为空则阻止其他读取器被执行)也不应该那么困难。