本文根据 文章 http://blog.csdn.net/exceptional_derek/article/details/40384659 整理。
ConcurrentHashMap 是线程安全且较高效的Map结构。
下面分析一下 ConcurrentHashMap 为什么是线程安全的。
1、 putIfAbsent 方法
V putIfAbsent(K key,V value) : 如果指定键已经不再与某个值相关联,则将它与给定值关联。
putIfAbsent()方法用于在map中进行添加。这个方法以要添加到ConcurrentMap中的键的值为参数,就像普通的put()方法,但是只有在map不包含这个键时,才能将键加入到map中。如果map已经包含这个键,那么这个键的现有值就会保留。putIfAbsent()方法是原子的。等价于下面的代码(除了原子地执行此操作之外):
先看一段代码:
- public class Locale {
- private final static Map<String, Locale> map = new HashMap<String,Locale>();
- public static Locale getInstance(String language, String country,
- String variant) {
- //...
- String key = some_string;
- Locale locale = map.get(key);
- if (locale == null) {
- locale = new Locale(language, country, variant);
- map.put(key, locale);
- }
- return locale;
- }