问题
I would like to know the possible scenarios that can occur when we are trying to read a ConcurrentHashMap while it is resizing.
I know that during read, first attempt is always unsynchronized. In second attempt it will try to acquire lock and retry.
But if it happens during resizing how would it work?
Thanks
回答1:
By looking at the source:
A ConcurrentHashMap contains one or more segments, depending on the concurrency level.
During a rehash, a segment is locked and the new table is built next to the old table then replaces it at the end.
If you call get()
during the rehash of a segment and your key is stored in that segment, you will access the old table of the segment without lock and if found and the value is not null, it will be returned. If the value is null, the call will block until the rehash is done and the value will be read again under lock.
来源:https://stackoverflow.com/questions/44009989/concurrenthashmap-read-while-resizing