Java中的ConcurrentHashMap? [英] ConcurrentHashMap in Java?

查看:88
本文介绍了Java中的ConcurrentHashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中使用 ConcurrentHashMap 有什么用?它有什么好处?它是如何工作的?
示例代码也很有用。

What is the use of ConcurrentHashMap in Java? What are its benefits? How does it work? Sample code would be useful too.

推荐答案

重点是提供的实现HashMap 这是线程安全的。多个线程可以读取和写入它,而不会接收过时或损坏的数据。 ConcurrentHashMap 提供了自己的同步,因此您不必显式同步对它的访问。

The point is to provide an implementation of HashMap that is threadsafe. Multiple threads can read from and write to it without the chance of receiving out-of-date or corrupted data. ConcurrentHashMap provides its own synchronization, so you do not have to synchronize accesses to it explicitly.

ConcurrentHashMap 是它提供 putIfAbsent 方法,如果指定了原子添加映射密钥不存在。请考虑以下代码:

Another feature of ConcurrentHashMap is that it provides the putIfAbsent method, which will atomically add a mapping if the specified key does not exist. Consider the following code:

ConcurrentHashMap<String, Integer> myMap = new ConcurrentHashMap<String, Integer>();

// some stuff

if (!myMap.contains("key")) {
  myMap.put("key", 3);
}

此代码不是线程安全的,因为另一个线程可以为<$添加映射c $ c>key在的调用中包含和对的调用 。正确的实现方式是:

This code is not threadsafe, because another thread could add a mapping for "key" between the call to contains and the call to put. The correct implementation would be:

myMap.putIfAbsent("key", 3);

这篇关于Java中的ConcurrentHashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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