并发hashMap putIfAbsent方法功能 [英] concurrent hashMap putIfAbsent method functionality

查看:613
本文介绍了并发hashMap putIfAbsent方法功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am a new bie to the world of java and exploring the concurrent hash map, while exploring the concurrent hashmap API , I discover the putifAbsent() method

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

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

Now please advise what is it functionality and when do we practically require it , if possible please explain with a small simple example.

推荐答案

A ConcurrentHashMap 是设计使它可以被大量的并发线程使用。

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

现在,如果你使用了标准 Map 界面提供的方法你可能会写这样的东西

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

这看起来不错,似乎可以胜任,但它是不是线程安全的。所以你会想,啊,但我知道 synchronized 关键字并将其改为此

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

解决了这个问题。

现在您所做的是锁定整个地图以便读取和写入,同时检查密钥是否存在,然后将其添加到地图。

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.

所以,你使用JDK提供的解决方案。

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

ConcurrentHashMap 是一个聪明的实现,它将 Map 划分为区域并单独锁定它们,以便您可以对映射进行并发,线程安全,读取和写入没有外部锁定。

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.

与实现中的所有其他方法一样 putIfAbsent 锁定密钥的区域而不是整个 Map 因此允许在此期间其他地区继续进行其他活动。

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.

这篇关于并发hashMap putIfAbsent方法功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆