简体   繁体   中英

ConcurrentHashMap value iterator can it return null

I'm trying to understand the iterator code to ConcurrentHashMap and based on looking at the code it seems that it's possible for the ConcurrentHashMap#values()#iterator to return a null value.

I believe this can happen because, even though you can't add a null value, a call to remove will first mark a value as null.

Is this true or does the iterator have a way of handling this?

Looking at how get() is implemented, it seems that ConcuurrentHashMap is coded to allow for a situation where the entry value is null due to a class initialization race (which is then handled via a call to Segment.readValueUnderLock() . it appears that the value iterator does not ever check a value entry for null , so it seems you have a valid question (i don't know if there is some other volatile operation which happens during iteration which would alter this possibility).

However, there is this javadoc note on the Segment.readValueUnderLock() method:

Reads value field of an entry under lock. Called if value field ever appears to be null. This is possible only if a compiler happens to reorder a HashEntry initialization with its table assignment, which is legal under memory model but is not known to ever occur.

(last emphasis mine).

Probably would be a good question for Doug Lea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM