Я рассматриваю реализацию 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 может быть назначена на вкладку [...] до того, как она будет построена полностью (поэтому результат может видеть другие потоки, но e.value может быть нулевым)?
Update: Я прочитал эту статью, и это хорошо. Но мне нужно заботиться о таком случае
ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue();
thread1:
Person p=new Person("name","student");
queue.offer(new Person());
thread2:
Person p = queue.poll();
Есть ли вероятность того, что thread2 получит объект объекта незавершенной конструкции Person, как HashEntry в
tab [index] = new HashEntry (ключ, хэш, первый, значение);