ConcurrentHashMap 重新排序指令?
我正在研究 ConcurrentHashMap 的实现,有一件事让我感到困惑。
/* Specialized implementations of map methods */
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;
}
和
/**
* 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.
*/
V readValueUnderLock(HashEntry<K,V> e) {
lock();
try {
return e.value;
} finally {
unlock();
}
}
和 HashEntry 构造函数
/**
* ConcurrentHashMap list entry. Note that this is never exported
* out as a user-visible Map.Entry.
*
* Because the value field is volatile, not final, it is legal wrt
* the Java Memory Model for an unsynchronized reader to see null
* instead of initial value when read via a data race. Although a
* reordering leading to this is not likely to ever actually
* occur, the Segment.readValueUnderLock method is used as a
* backup in case a null (pre-initialized) value is ever seen in
* an unsynchronized access method.
*/
static final class HashEntry<K,V> {
final K key;
final int hash;
volatile V value;
final HashEntry<K,V> next;
HashEntry(K key, int hash, HashEntry<K,V> next, V value) {
this.key = key;
this.hash = hash;
this.next = next;
this.value = value;
}
把实现
tab[index] = new HashEntry<K,V>(key, hash, first, value);
我对HashEntry的评论感到困惑,作为JSR-133,一旦构建了HashEntry,所有最终字段都将对所有其他线程可见,值字段是易失性的,所以我认为它对其他线程也是可见的???.另一点,他所说的重新排序是:HashEntry对象引用可以在完全构造之前分配给tab[...](所以结果是其他线程可以看到这个条目,但e.value可以是空的)?
更新:我读了这篇文章,它很好。但是我需要关心这样的案例吗?
ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue();
thread1:
Person p=new Person("name","student");
queue.offer(new Person());
thread2:
Person p = queue.poll();
线程 2 是否有可能收到未完成构造的 Person 对象,就像 HashEntry 中的一样
tab[index] = new HashEntry(key, hash, first, value); ?