简体   繁体   English

在并发哈希图中读写

[英]Read and write in a concurrenthashmap

I have doubt understanding concurrenthashmap .我对理解 concurrenthashmap 有疑问。 If a section of conc hashmap is locked up by a writer thread then is it possible for a reader thread to read the same section of hashmap map simultaneously ?如果 conc hashmap 的一部分被写入线程锁定,那么读取线程是否有可能同时读取 hashmap 映射的同一部分? or does it need the lock to be released from the writer thread ?还是需要从写线程释放锁?

If you look at the source code of ConcurrentHashMap.get() then you can easily understand it.如果您查看ConcurrentHashMap.get()的源代码,那么您可以轻松理解它。

No lock is required while reading from concurrent map but if the value is null it checks again under readValueUnderLock从并发映射读取时不需要锁,但如果值为null它会在readValueUnderLock下再次检查

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

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

Look at the ConcurrentHashMap.put() method as well that first calls lock() and finally calls unlock()看看ConcurrentHashMap.put()方法,首先调用lock()最后调用unlock()

    put(K key, int hash, V value, boolean onlyIfAbsent) {
         lock();
         try {
            ...
         } finally {
             unlock();
         }
     }

读取不需要锁。更新地图需要锁。

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

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