The TreeBin of ConcurrentHashMap maintains a parasitic read-write lock. Who can tell me why there maintains a read-write lock?
There is a comment in the code that explains the TreeBin parasitic locking strategy like this:
/*
* 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.
*/
The "why" is explained by this later comment:
/**
* 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.
*/
In short, the overall locking strategy is to avoid locking on read paths. So the map is divided into "bins", and each bin has a many reader / single writer lock.
Except that readers don't actually get blocked if there is lock contention. Instead, they traverse the entire bin ... checking back to see if lock has been released. The "parasitic" locking is the implementation of that.