Reputation: 954
I'm reading reading the source code of java.util.ConcurrentHashMap and find that the next
field in ConcurrentHashMap$HashEntry is final. There are two operations that is possible to modify the value of next
:add and remove. But those two operations cat be done thread safely even though the next
field is not final. So I cann't understand why the next
field is final, can anyone tell me why? thanks.
Upvotes: 1
Views: 284
Reputation: 242716
final
on next
is needed to ensure that reading threads see the initialized value of the field, because (most of) reads of ConcurrentHashMap
happen without synchronization.
Note that, for example, value
is not final
, therefore reading thread can see a non-initialized value (null
) in that field, and have to recheck it under synchronization in that case:
V get(Object key, int hash) {
if (count != 0) { // read-volatile
HashEntry<K,V> e = getFirst(hash);
while (e != null) {
if (e.hash == hash && key.equals(e.key)) {
V v = e.value;
if (v != null)
return v;
return readValueUnderLock(e); // recheck
}
e = e.next;
}
}
return null;
}
Upvotes: 1