在Java中使用什么策略进行分层重入读/写锁定?

Jea*_*let 7 java locking hierarchical reentrancy readwritelock

我正在寻找高效的系统,以便分层组织一系列读/写锁,以管理对分层组织资源的访问.如果一个子树被锁定以进行写入,那么在它被释放之前,不应该在整个子树中获得其他锁定; 类似地,子树中的写锁定应该防止在父节点中锁定.

以下是我正在考虑的想法:

  • 使用Apache Commons Transaction.不幸的是,该项目自2008年3月以来一直没有更新,并且已经非正式终止.一些API文档似乎表明即将推出的版本(1.3或2.0)将包含某种层次锁定,但源代码无处可寻,似乎我们无法再访问其SVN存储库.

  • 使用一系列ReentrantReadWriteLocks,我将按层次结构组织.我不是并发专家,我有点害怕自己这样做.初步想法似乎表明,即使在我尝试锁定一个子树之前,我必须在管理ReentrantReadWriteLocks本身的整个结构上使用外锁- 这样即使释放一个锁,我也必须使用外锁...

  • 使用来自java.util.concurrentjava.util.concurrent.atomic实现我的分层锁的类比我用一系列ReentrantReadWriteLocks 更有效.

我已经准备好走最后一条路,但我很惊讶没有找到任何可以更好地解决这个问题的现有图书馆.所以:

  • 我错过了一些明显的解决方案?
  • 或者这个问题特别难以妥善解决?

Kru*_*Kru 4

我不知道我是否理解你的问题,正如你所说,当你锁定子树进行写入时,整个结构都被锁定。因此,一种简单的解决方案是为整个结构设置一个 RW 锁。

顺便说一句,java.util.concurrent.atomic除了 RW 锁树之外,它不会对你有更多帮助。


如果您希望能够独立锁定同级,您可以采用第二种解决方案(锁树,其中每个节点都有对其父节点的引用)。

锁定一个节点将使用其写锁来锁定它,并使用读锁来锁定每个父节点。当子级被锁定时,父级不能被锁定,因为您无法获取其写锁,因为锁定子级已经获取了读锁。仅当没有其他线程对任何父线程进行写锁定时才允许锁定子线程。

上面描述的锁是排它锁。 (读写锁的另一个名称是共享独占锁)

要添加共享锁,每个节点还需要一个原子整数来指示:如果为正,则为间接写锁定子节点的数量;如果为正,则为间接写锁定子节点的数量。如果为负数,则表示节点被读锁定的次数。此外,节点及其父节点将被读锁定,以避免在父节点上获取新的写锁。

伪代码:

Node {
    // fields
    parent: Node
    lock: RWLock
    count: AtomicInteger
}

public boolean trylocktree(node: Node, exclusive: boolean) {
    if (exclusive) {
        return trylocktree_ex(node, true);
    } else {
        return trylocktree_sh(node);
    }
}
private boolean switch_count(i: AtomicInteger, diff: int) {
    // adds diff to i if the sign of i is the same as the sign of diff
    while (true) {
        int v = i.get();
        if (diff > 0 ? v < 0 : v > 0)
            return false;
        if (i.compareAndSet(v, v + diff))
            return true;
    }
}
private boolean trylocktree_ex(node: Node, writing: boolean) {
    // check if a node is read-locked
    if (!switch_count(node.count, 1))
        return false;
    // lock using the lock type passed as an arg
    if (!node.lock(writing).trylock()) {
        node.count--;
        return false;
    }
    // read-lock every parent
    if (!trylocktree_ex(node.parent, false)) {
        node.count--
        node.lock(writing).unlock();
        return false;
    }
    return true;
}
private boolean trylocktree_sh(node: Node) {
    // mark as shared-locked subtree
    if (!switch_count(node.count, -1))
        return false;
    // get shared-lock on parents
    if (!readlock_recursively(node)) {
        node.count++;
        return false;
    }
    return true;
}
private boolean readlock_recursively(node: Node) {
    if (!node.lock(false).trylock())
        return false;
    if (!readlock_recursively(node.parent)) {
        node.lock(false).unlock();
        return false;
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

如果无法获取任何锁定,则解锁已锁定的内容并稍后重试(可以使用全局条件变量、超时等来实现此目的)。

编辑:添加代码来读锁定/写锁定树