search

Home  >  Q&A  >  body text

java - concurrentHashMap源码中的readValueUnderLock(e)存在的意义?

巴扎黑巴扎黑2872 days ago927

reply all(3)I'll reply

  • 迷茫

    迷茫2017-04-18 10:06:43

    e.hash == hash && key.equals(e.key)

    The previous sentence explains that when there is this key的,你看看put方法,当valuenull in the table, an exception will occur:

    public V put(K key, V value) {
            Segment<K,V> s;
            if (value == null)
                throw new NullPointerException();
            int hash = hash(key);
            int j = (hash >>> segmentShift) & segmentMask;
            if ((s = (Segment<K,V>)UNSAFE.getObject          // nonvolatile; recheck
                 (segments, (j << SSHIFT) + SBASE)) == null) //  in ensureSegment
                s = ensureSegment(j);
            return s.put(key, hash, value, false);
        }

    This is a higher version of mine. It may be different from yours, but the value cannot be empty.
    So:

    if (v != null)
        return v;
    return readValueUnderLock(e); // recheck

    If it is not empty, it can be returned directly. If it is empty, it means that other threads are operating it. So I added it.

    public V get(Object key) {
            Segment<K,V> s; // manually integrate access methods to reduce overhead
            HashEntry<K,V>[] tab;
            int h = hash(key);
            long u = (((h >>> segmentShift) & segmentMask) << SSHIFT) + SBASE;
            if ((s = (Segment<K,V>)UNSAFE.getObjectVolatile(segments, u)) != null &&
                (tab = s.table) != null) {
                for (HashEntry<K,V> e = (HashEntry<K,V>) UNSAFE.getObjectVolatile
                         (tab, ((long)(((tab.length - 1) & h)) << TSHIFT) + TBASE);
                     e != null; e = e.next) {
                    K k;
                    if ((k = e.key) == key || (e.hash == h && key.equals(k)))
                        return e.value;
                }
            }
            return null;
        }

    The current versionget方法把HashEntry<K,V> e弄成UNSAFE.getObjectVolatile()获取,像是volatile is out

    reply
    0
  • 阿神

    阿神2017-04-18 10:06:43

    The poster can upgrade the JDK, I use it 1.8找了一下,没发现这段代码在ConcurrentHashMap.

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 10:06:43

    The object is null when it is initialized. This null is not assigned specifically in the program.

    reply
    0
  • Cancelreply