是否有一个带有java监听器的读写锁?

时间:2015-04-05 15:47:54

标签: java concurrency java-8

是否有一个java库可以实现类似ReadWriteLock的行为,但使用侦听器或CompletableFuture / CompletionStage而不是阻塞?

理想情况下我想写:

lock = ...

CompletionStage stage = lock.lockRead();
stage.thenAccept(r -> { doSomething(); r.release(); });

同样重要的是:

CompletionStage stage = lock.tryLockWrite(10, TimeUnit.SECONDS);
stage.handle(callback);

我想知道这样的事情是否存在以及是否如何调用

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

1 个答案:

答案 0 :(得分: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);
    }
}

添加定时锁定(通过使用某种&#34;到期队列&#34;或写入者饥饿预防(通过阻止其他读者被执行,如果queueWriters不为空)到上面不应该&#39 ;也是那么困难。