简体   繁体   English

ConcurrentHashMap每次读取都锁定?

[英]ConcurrentHashMap Locking at every read?

I wanted to understand how does locking work in Java ConcurrentHashMap. 我想了解锁定在Java ConcurrentHashMap中是如何工作的。 Accordingly to the source-code here , it looks like for every read it is locking the reader using the lock of that particular segment. 根据此处的源代码,看起来对于每次读取,它都使用该特定段的锁来锁定读取器。 Have I got it wrong? 我看错了吗?

V readValueUnderLock(HashEntry<K,V> e) {
    lock();
         try {
             return e.value;
         } finally {
             unlock();
         }
     }

Every Read is not locked below is documentation of method readValueUnderLock 每次读取均未锁定,下面是方法readValueUnderLock的文档

Reads value field of an entry under lock. 读取处于锁定状态的条目的值字段。 Called if value field ever appears to be null . 如果value字段曾经显示为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 . 仅当编译器碰巧使用表分配对HashEntry初始化进行重新排序时才有可能,这在内存模型下合法的,但从未发生过

Read in a ConcurrentHashMap does not synchronize on the entire map. 读入ConcurrentHashMap不会在整个地图上同步。 Infact traversal does not synchronize at all except under one condition. 除了一种情况外,事实遍历根本不同步。 The internal LinkedList implementation is aware of the changes to the underlying collection. 内部LinkedList实现知道对基础集合的更改。 If it detects any such changes during traversal it synchronizes itself on the bucket it is traversing and then tries to re-read the values. 如果在遍历期间检测到任何此类更改,它将在正在遍历的存储桶中进行自身同步,然后尝试重新读取值。 This always insures that while the values received are always fresh, there is minimalistic locking if any. 这始终可以确保尽管接收到的值始终是最新的,但存在最小锁定(如果有)。

Below is get implementation in this class readValueUnderLock is called only when v is null 下面是此类的get实现,仅当v为null时才调用readValueUnderLock

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM