我正在研究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构建完成,所有其他线程都将可见所有final字段,字段是 volatile 的,所以我认为它也对其他线程可见??? 。还有一点,他说的重新排序是否是:HashEntry对象引用可以在完全构建之前分配给tab [...](因此结果是其他线程可以看到此条目,但是e.value可以为null)?

更新:
我读了this文章,很好。但是我需要关心这样的情况吗
ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue();

thread1:

Person p=new Person("name","student");
queue.offer(new Person());

thread2:
Person p = queue.poll();

是否有可能thread2收到未完成构造的Person对象,就像HashEntry中的

最佳答案

对于那些对Doug Lea对此主题的回答感兴趣的人,他最近解释了readValueUnderLock的原因

这是对有人提出以下问题的答复:



回复:



可以全部查看here

10-04 21:41