I am wondering how does ConcurrentHashMap handle rehashing while another thread is still writing on another segment/partition.
As far as I understand, ConcurrentHashMap locks the segment independently, so for example:
If Thread1 writes to the segment1 slightly before Thread2 writes to segment2, then what happens if it requires the table to resize and rehash after Thread1 insertion, but Thread2 is in the middle of the writing operation?
Does it lock the whole map for rehashing? And does it have something like "tell Thread2 to stop and wait until the rehash is done"? Because Thread2 may have a chance to end up writing segment1 after the table resize, correct?
Every segment is separately rehashed so there is no collision.
ConcurrentHashMapis array of specialized hash tables which are calledSegmentsFrom the source code
And if you check the method which returns Segment
So if you call
putit first determines theSegmentusingsegmentForand then call put on thatSegmentputsource code