为什么 TreeBin 在 ConcurrentHashMap 中维护一个读写锁?

why TreeBin maintains a read-write lock in ConcurrentHashMap?

ConcurrentHashMap的TreeBin维护着一个寄生读写锁。谁能告诉我为什么要维护读写锁?

代码中有注释是这样解释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.
 */

"why" 由后面的评论解释:

/**
 * 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.
 */

简而言之,总体锁定策略是避免在读取路径上锁定。所以map分为"bins",每个bin有很多reader / single writer lock.

除了 reader 如果存在锁争用实际上不会被阻塞。相反,他们遍历整个箱子……回头检查锁是否已被释放。 "parasitic" 锁定就是它的实现。