为什么TreeBin在ConcurrentHashMap中保持读写锁定?

时间:2018-09-30 02:28:25

标签: java concurrenthashmap

ConcurrentHashMap的TreeBin维护一个寄生读写锁。谁能告诉我为什么那里保持读写锁定?

1 个答案:

答案 0 :(得分:0)

代码中有一条注释,说明了TreeBin寄生锁定策略,如下所示:

/*
 * TreeBins also require an additional locking mechanism.  While
 * list traversal is always possible by readers even during
 * updates, tree traversal is not, mainly because of tree-rotations
 * that may change the root node and/or its linkages.  TreeBins
 * include a simple read-write lock mechanism parasitic on the
 * main bin-synchronization strategy: Structural adjustments
 * associated with an insertion or removal are already bin-locked
 * (and so cannot conflict with other writers) but must wait for
 * ongoing readers to finish. Since there can be only one such
 * waiter, we use a simple scheme using a single "waiter" field to
 * block writers.  However, readers need never block.  If the root
 * lock is held, they proceed along the slow traversal path (via
 * next-pointers) until the lock becomes available or the list is
 * exhausted, whichever comes first. These cases are not fast, but
 * maximize aggregate expected throughput.
 */

后面的注释解释了“为什么”:

/**
 * TreeNodes used at the heads of bins. TreeBins do not hold user
 * keys or values, but instead point to list of TreeNodes and
 * their root. They also maintain a parasitic read-write lock
 * forcing writers (who hold bin lock) to wait for readers (who do
 * not) to complete before tree restructuring operations.
 */
简而言之,总体锁定策略是避免锁定读取路径。因此,将地图分为“箱”,每个箱具有多个读取器/单个写入器锁。

除非存在锁争用,否则实际上不会阻止读者。取而代之的是,他们遍历整个垃圾箱...然后检查以查看是否已释放锁定。 “寄生”锁定就是这种实现。