java.util.concurrent提供并发集合(concurrent collection)。有些集合的接口通过依赖状态的修改操作(state-dependent modify operation)进行扩展,将几个基本操作合并到单个原子操作中。例如,map接口putIfAbsent(String key, Object value)。
背景与正确使用。
先看一段代码:
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;
}
// ....
}
这段代码要做的事情是:调用 map.get(key) 方法,判断 map 里面是否有该 key 对应的 value (Locale 对象)。
如果返回 null,表示 map 里面没有要查找的 key-value mapping。new 一个 Locale 对象,并把 new 出来的这个对象与 key 一起放入 map。最后返回新创建的 Locale 对象。
我们期望每次调用 getInstance 方法时要保证相同的 key 返回同一个 Local 对象引用。那么,单看第一段代码,请问它能实现这个期望么?
答案是:在单线程环境下可以满足要求,但是在多线程环境下会存在线程安全性问题,即不能保证在并发的情况相同的 key 返回同一个 Local 对象引用。
这是因为在上面的代码里存在一个习惯被称为 put-if-absent 的操作,而这个操作存在一个 race condition:
因为在某个线程做完 locale == null 的判断到真正向 map 里面 put 值这段时间,其他线程可能已经往 map 做了 put 操作,这样再做 put 操作时,同一个 key 对应的 locale 对象被覆盖掉,最终 getInstance 方法返回的同一个 key 的 locale 引用就会出现不一致的情形。所以对 Map 的 put-if-absent 操作是不安全的(thread safty)。/**
* If the specified key is not already associated
* with a value, associate it with the given value.
* This is equivalent to
* * if (!map.containsKey(key))
* return map.put(key, value);
* else
* return map.get(key);
* except that the action is performed atomically.
* .....
*/
public final class Locale implements Cloneable, Serializable {
// cache to store singleton Locales
private final static ConcurrentHashMap<String, Locale> cache = new ConcurrentHashMap<String, Locale>(32);
static Locale getInstance(String language, String country, String variant) {
if (language== null || country == null || variant == null) {
throw new NullPointerException();
}
StringBuilder sb = new StringBuilder();
sb.append(language).append('_').append(country).append('_').append(variant);
String key = sb.toString();
Locale locale = cache.get(key);
if (locale == null) {
locale = new Locale(language, country, variant);
Locale l = cache.putIfAbsent(key, locale);
if (l != null) {
locale = l;
}
}
return locale;
}
// ....
}