轉自:http://blog.csdn.net/exceptional_derek/article/details/40384659
先看一段代碼:
- 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 的操作 [1],而這個操作存在一個 race condition:
- if (locale == null) {
- locale = new Locale(language, country, variant);
- map.put(key, locale);
- }
因為在某個線程做完 locale == null 的判斷到真正向 map 里面 put 值這段時間,其他線程可能已經往 map 做了 put 操作,這樣再做 put 操作時,同一個 key 對應的 locale 對象被覆蓋掉,最終 getInstance 方法返回的同一個 key 的 locale 引用就會出現不一致的情形。所以對 Map 的 put-if-absent 操作是不安全的(thread safty)。
為了解決這個問題,java 5.0 引入了 ConcurrentMap 接口,在這個接口里面 put-if-absent 操作以原子性方法 putIfAbsent(K key, V value) 的形式存在。正如 javadoc 寫的那樣:
- /**
- * If the specified key is not already associated
- * with a value, associate it with the given value.
- * This is equivalent to
- * <pre>
- * if (!map.containsKey(key))
- * return map.put(key, value);
- * else
- * return map.get(key);</pre>
- * except that the action is performed atomically.
- * .....
- */
所以可以使用該方法替代上面代碼里的操作。但是,替代的時候很容易犯一個錯誤。請看下面的代碼:
- public class Locale implements Cloneable, Serializable {
- private final static ConcurrentMap<String, Locale> map = new ConcurrentHashMap<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.putIfAbsent(key, locale);
- }
- return locale;
- }
- // ....
- }
這段代碼使用了 Map 的 concurrent 形式(ConcurrentMap、ConcurrentHashMap),並簡單的使用了語句map.putIfAbsent(key, locale) 。這同樣不能保證相同的 key 返回同一個 Locale 對象引用。
這里的錯誤出在忽視了 putIfAbsent 方法是有返回值的,並且返回值很重要。依舊看 javadoc:
- /**
- * @return the previous value associated with the specified key, or
- * <tt>null</tt> if there was no mapping for the key.
- * (A <tt>null</tt> return can also indicate that the map
- * previously associated <tt>null</tt> with the key,
- * if the implementation supports null values.)
- */
“如果(調用該方法時)key-value 已經存在,則返回那個 value 值。如果調用時 map 里沒有找到 key 的 mapping,返回一個 null 值”
所以,使用 putIfAbsent 方法時切記要對返回值進行判斷。如下所示(java.util.Locale 類中的實現代碼):
- 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;
- }
- // ....
- }
與前段代碼相比,增加了對方法返回值的判斷:
- Locale l = cache.putIfAbsent(key, locale);
- if (l != null) {
- locale = l;
- }
這樣可以保證並發情況下代碼行為的准確性。
-------------------------------------------------