Home  >  Q&A  >  body text

java - Why can the get() method in ConcurrentHashMap not be locked?

 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;
    }

Why does Vector's get require synchronized locking but ConcurrentHashMap does not? Moreover, CopyOnWriteArrayList also uses copy-on-write to achieve parallel reading and writing. Obviously, ConcrrentHashMap does not implement copy-on-write. How does it ensure that inconsistent intermediate states will not be read during parallel reading and writing?

漂亮男人漂亮男人2734 days ago850

reply all(1)I'll reply

  • PHPz

    PHPz2017-05-17 10:02:31

    This article explains it very well

    reply
    0
  • Cancelreply