在Java中使用什么策略进行分层重入读/写锁定?
我正在寻找一个高效的系统来分层组织一系列读/写锁来管理对分层组织资源的访问.如果一个子树被锁定以进行写入,那么在整个子树中都不能获得其他锁定,直到它被释放为止;类似地,子树中的写锁定应该防止锁定父节点.
以下是我正在考虑的想法: >使用Apache Commons Transaction.不幸的是,该项目自2008年3月以来一直没有更新,并且已经非正式终止.一些API文档似乎表明即将推出的版本(1.3或2.0)将包括some kind of hierarchical locking,但是无法找到源代码,似乎我们无法再访问其SVN存储库. 我已经准备好走最后一条路,但我很惊讶没有找到任何可以更好地解决这个问题的现有库.所以: >我错过了一些明显的解决方案吗? 解决方法
我不知道我是否理解你的问题,正如你所说当你锁定一个子树进行写入时,整个结构都被锁定了.
因此,简单的解决方案是为整个结构设置一个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; } 如果无法获取任何锁定,则解锁锁定的内容并稍后重试(可以使用全局条件变量,超时等来实现此目的). 编辑:添加代码以读取锁定/写入锁定树 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |