在concurrenthashmap中读写

问题描述 投票:-1回答:2

我怀疑了并发hashmap。如果conc hashmap的一部分被编写器线程锁定,那么读者线程是否可以同时读取同一部分的hashmap映射?或者它是否需要从作者线程中释放锁?

java multithreading concurrenthashmap
2个回答
1
投票

如果你查看ConcurrentHashMap.get()的源代码,那么你可以很容易地理解它。

从并发映射读取时不需要锁定,但如果值为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();
         }
     }

看看ConcurrentHashMap.put()方法,首先调用lock(),最后调用unlock()

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

0
投票

读取时无需锁定。更新地图需要锁定。

© www.soinside.com 2019 - 2024. All rights reserved.