2

我是 Java 世界的新手,正在探索并发哈希映射,在探索并发哈希映射 API 时,我发现了 putifAbsent() 方法

public V putIfAbsent(K paramK, V paramV)
  {
    if (paramV == null)
      throw new NullPointerException();
    int i = hash(paramK.hashCode());
    return segmentFor(i).put(paramK, i, paramV, true);
  }

现在请告知它的功能是什么,我们什么时候需要它,如果可能的话,请用一个简单的小例子来解释。

4

3 回答 3

16

A ConcurrentHashMap is designed so that it can be used by a large number of concurrent Threads.

Now, if you used the methods provided by the standard Map interface you would probably write something like this

  if(!map.containsKey("something")) {
      map.put("something", "a value");
  }

This looks good and seems to do the job but, it is not thread safe. So you would then think, "Ah, but I know about the synchronized keyword" and change it to this

  synchronized(map) {
      if(!map.containsKey("something")) {
          map.put("something", "a value");
      }
  }

Which fixes the issue.

Now what you have done is locked the entire map for both read and write while you check if the key exists and then add it to the map.

This is a very crude solution. Now you could implement your own solution with double checked locks and re-locking on the key etc. but that is a lot of very complicated code that is very prone to bugs.

So, instead you use the solution provided by the JDK.

The ConcurrentHashMap is a clever implementation that divides the Map into regions and locks them individually so that you can have concurrent, thread safe, reads and writes of the map without external locking.

Like all other methods in the implementation putIfAbsent locks the key's region and not the whole Map and therefore allows other things to go on in other regions in the meantime.

于 2013-04-06T12:20:57.140 回答
1

ConcurrentHashMap is used when several threads may access the same map concurrently. In that case, implementing putIfAbsent() manually, like below, is not acceptable:

if (!map.containsKey(key)) {
    map.put(key, value);
} 

Indeed, two threads might execute the above block in parallel and enter in a race condition, where both first test if the key is absent, and then both put their own value in the map, breaking the invariants of the program.

The ConcurrentHashMap thus provides the putIfAbsent() operation which makes sure this is done in an atomic way, avoiding the race condition.

于 2013-04-06T12:21:44.657 回答
0

想象一下,我们需要一个惰性初始化的命名单例 bean 的缓存。下面是一个基于 ConcurrentHashMap 的无锁实现:

ConcurrentMap<String, Object> map = new ConcurrentHashMap<>();

<T> T getBean(String name, Class<T> cls) throws Exception {
    T b1 = (T) map.get(name);
    if (b1 != null) {
        return b1;
    }
    b1 = cls.newInstance();
    T b2 = (T) map.putIfAbsent(name, b1);
    if (b2 != null) {
        return b2;
    }
    return b1;
}

请注意,它解决了与双重检查锁定相同的问题,但没有锁定。

于 2013-04-06T13:01:54.423 回答