Reputation: 1663
As I understand, put()
, clear()
and remove()
are provided by ConcurrentHashMap
and it is thread safe operation without using any locks.
In ConcurrentHashMap
, there are different segments and for each segment there are several hash buckets.
Clear()
and put()
are thread safe because clear()
just clear the reference to the hash chain for that bucket but the hash chain is still there, so if thread A is iterating over it, it will not be affected but clear()
from thread B. Put()
will always put a new node at the beginning of the hash chain for that bucket, so it is fine also.
However,What I don't understand is that why remove()
will be thread safe? For example, the hash bucket is bucket->A->B->C->D->E and thread A calls remove(C)
, the mechanism provided by the implementation of the ConcurrentHashMap
is to copy A, B into a next linked list but in reverse order bucket->B->A->D-E and then make A.next to the original D->E which result in bucket->B->A->D-E.
Why this is thread safe? What if thread B
is currently iterating over element A and then thread A
calls remove(C). Looks like it will break?
Upvotes: 2
Views: 1336
Reputation: 1098
Well, remove() clones HashEntry elements up to removed element, not modifies old ones. So you get
B*->A*->D->E in bucket, but original
A->B->C-^ sequence is not touched.
You can be sure that A.equals(A*) == false, even though they will have equal keys and equal values. But that's not a problem for iterator as it simply uses already aquired entry A to move on.
P.S. ConcurrentHashMap uses locks on bucket level for modifications. It's not lock-free.
Upvotes: 2