先看一段代码:
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; }
这样可以保证并发情况下代码行为的准确性。
-------------------------------------------------
本文写的内容源于今天阅读 java.util.DateFormat 源码时碰到的一个用法,更准确的说,这个用法出现在 java SE 6 的 java.util.Locale 类的 getInstance(String language, String country, String variant) 方法实现部分。
加之前阵子刚看过 FindBugs 的某个 ppt [2],ppt 上举了几个 Java 程序员容易犯错的代码写法的例子,其中一个就是忽视ConcurrentMap.putIfAbsent 方法返回值的情况。
最后,借用 ppt 上给的关于这个错误的 lessons(经验教训):
- Concurrency is tricky
- putIfAbsent is tricky to use correctly
- engineers at Google got it wrong more than 10% of the time
- Unless you need to ensure a single value, just use get followed by put if not found
- If you need to ensure a single unique value shared by all threads, use putIfAbsent and Check return value
-------------------------------------------
参考:
[1] Java Concurrency in Practice. by Brian Goetz, Tim Peierls, Joshua Bloch el.
[2] Defective Java Code: Mistakes That Matter. by William Pugh
相关推荐
主要介绍了ConcurrentMap.putIfAbsent(key,value)用法实例,分享了相关代码示例,小编觉得还是挺不错的,具有一定借鉴价值,需要的朋友可以参考下
5.Lock-free:atomic、concurrentMap.putIfAbsent、CopyOnWriteArrayList 6.关于锁的经验介绍 7.并发流程控制手段:CountDownLatch、Barrier 8.定时器:ScheduledExecutorService、大规模定时器TimerWheel 9.并发三...
Concurrent.Thread.js 一个用来让javascript也进行多线程开发的包,感兴趣的快来下吧。
5、Lock-free: atomic、concurrentMap.putIfAbsent、CopyOnWriteArrayList ☆ ☆ ☆ 6、关于锁使用的经验介绍 7、并发流程控制手段:CountDownlatch、Barrier 8、定时器: ScheduledExecutorService、大规模定时器...
5、Lock-free: atomic、concurrentMap.putIfAbsent、CopyOnWriteArrayList☆☆☆ 6、关于锁使用的经验介绍 7、并发流程控制手段:CountDownlatch、Barrier 8、定时器: ScheduledExecutorService、大规模定时器...
5、Lock-free: atomic、concurrentMap.putIfAbsent、CopyOnWriteArrayList☆☆☆ 6、关于锁使用的经验介绍 7、并发流程控制手段:CountDownlatch、Barrier 8、定时器: ScheduledExecutorService、大规模定时器...
concurrentMap := concurrentmap . New ( concurrentmap . WithBucket ( 32 )) concurrentMap . Store ( "1" , 1 ) if v , ok := concurrentMap . Load ( "1" ); ok { fmt . Printf ( " v = %v \n " , v ) ...
Practical Concurrent Haskell.pdf Practical Concurrent Haskell.pdf Practical Concurrent Haskell.pdf
concurrent.jar web开发工具包
CRC.Press.-.Creating.Components.-.Object.Oriented,.Concurrent,.and.Distributed.Computing.in.Java.-.2004.chm
Concurrent.Thread.js插件从各个版本都有,简单做了打包,资源分数不能设置为0,大家可以到我的百度云盘分享链接下载
介绍了一个可以在JavaScript中应用多线程的库:Concurrent.Thread,内有多线程库脚本,以及使用说明和实例,如果查看详情,可以查看我的博客https://blog.csdn.net/hsl_1990_08_15/article/details/84765772
开源项目-streamrail-concurrent-map.zip,Go中的仿制药
javax.enterprise.concurrent.* 含有 javax.enterprise.concurrent.ManagedThreadFactory类
Tomcat内存溢出的解决方法(java.util.concurrent.ExecutionException:java.lang.OutOfMemoryError),内附解决方案!
backport-util-concurrent.jarbackport-util-concurrent.jarbackport-util-concurrent.jar
Principles.of.Concurrent.and.Distributed.Programming.chm