concurrentHashMap
源码(JDK1.6)get
方法中为什么要readValueUnderLock(e)
,v
为null
究竟是怎么产生的?put
方法中有这么一段:tab[index] = new HashEntry<K,V>(key, hash, first, value);
难道在执行构造方法中会存在中间状态?value
还没有赋值就能读到?
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;
}
V readValueUnderLock(HashEntry<K,V> e) {
lock();
try {
return e.value;
} finally {
unlock();
}
}
楼主可以把JDK升级一下,我用的1.8
找了一下,没发现这段代码在ConcurrentHashMap
中。
对象初始的时候就是null,这个null并不是在程序中特意赋值的。