ConcurrentHashMap使用示例
如何快速提高你的薪资?-实力拍“跳槽吧兄弟”梦想活动即将开启
ConcurrentHashMap通常只被看做并发效率更高的Map,用来替换其他线程安全的Map容器,比如Hashtable和Collections.synchronizedMap。实际上,线程安全的容器,特别是Map,应用场景没有想象中的多,很多情况下一个业务会涉及容器的多个操作,即复合操作,并发执行时,线程安全的容器只能保证自身的数据不被破坏,但无法保证业务的行为是否正确。
举个例子:统计文本中单词出现的次数,把单词出现的次数记录到一个Map中,代码如下:
|
1
2
3
4
5
6
7
8
|
private final Map<String, Long> wordCounts = new ConcurrentHashMap<>();public long increase(String word) { Long oldValue = wordCounts.get(word); Long newValue = (oldValue == null) ? 1L : oldValue + 1; wordCounts.put(word, newValue); return newValue;} |
如果多个线程并发调用这个increase()方法,increase()的实现就是错误的,因为多个线程用相同的word调用时,很可能会覆盖相互的结果,造成记录的次数比实际出现的次数少。
除了用锁解决这个问题,另外一个选择是使用ConcurrentMap接口定义的方法:
|
1
2
3
4
5
6
|
public interface ConcurrentMap<K, V> extends Map<K, V> { V putIfAbsent(K key, V value); boolean remove(Object key, Object value); boolean replace(K key, V oldValue, V newValue); V replace(K key, V value);} |
这是个被很多人忽略的接口,也经常见有人错误地使用这个接口。ConcurrentMap接口定义了几个基于 CAS(Compare and Set)操作,很简单,但非常有用,下面的代码用ConcurrentMap解决上面问题:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
private final ConcurrentMap<String, Long> wordCounts = new ConcurrentHashMap<>();public long increase(String word) { Long oldValue, newValue; while (true) { oldValue = wordCounts.get(word); if (oldValue == null) { // Add the word firstly, initial the value as 1 newValue = 1L; if (wordCounts.putIfAbsent(word, newValue) == null) { break; } } else { newValue = oldValue + 1; if (wordCounts.replace(word, oldValue, newValue)) { break; } } } return newValue;} |
代码有点复杂,主要因为ConcurrentMap中不能保存value为null的值,所以得同时处理word不存在和已存在两种情况。
上面的实现每次调用都会涉及Long对象的拆箱和装箱操作,很明显,更好的实现方式是采用AtomicLong,下面是采用AtomicLong后的代码:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
private final ConcurrentMap<String, AtomicLong> wordCounts = new ConcurrentHashMap<>();public long increase(String word) { AtomicLong number = wordCounts.get(word); if (number == null) { AtomicLong newNumber = new AtomicLong(0); number = wordCounts.putIfAbsent(word, newNumber); if (number == null) { number = newNumber; } } return number.incrementAndGet();} |
这个实现仍然有一处需要说明的地方,如果多个线程同时增加一个目前还不存在的词,那么很可能会产生多个newNumber对象,但最终只有一个newNumber有用,其他的都会被扔掉。对于这个应用,这不算问题,创建AtomicLong的成本不高,而且只在添加不存在词是出现。但换个场景,比如缓存,那么这很可能就是问题了,因为缓存中的对象获取成本一般都比较高,而且通常缓存都会经常失效,那么避免重复创建对象就有价值了。下面的代码演示了怎么处理这种情况:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
private final ConcurrentMap<String, Future<ExpensiveObj>> cache = new ConcurrentHashMap<>();public ExpensiveObj get(final String key) { Future<ExpensiveObj> future = cache.get(key); if (future == null) { Callable<ExpensiveObj> callable = new Callable<ExpensiveObj>() { @Override public ExpensiveObj call() throws Exception { return new ExpensiveObj(key); } }; FutureTask<ExpensiveObj> task = new FutureTask<>(callable); future = cache.putIfAbsent(key, task); if (future == null) { future = task; task.run(); } } try { return future.get(); } catch (Exception e) { cache.remove(key); throw new RuntimeException(e); }} |
解决方法其实就是用一个Proxy对象来包装真正的对象,跟常见的lazy load原理类似;使用FutureTask主要是为了保证同步,避免一个Proxy创建多个对象。注意,上面代码里的异常处理是不准确的。
最后再补充一下,如果真要实现前面说的统计单词次数功能,最合适的方法是Guava包中AtomicLongMap;一般使用ConcurrentHashMap,也尽量使用Guava中的MapMaker或cache实现。
ConcurrentHashMap使用示例的更多相关文章
- HashMap、Hashtable、ConcurrentHashMap面试总结
原文链接:https://www.cnblogs.com/hexinwei1/p/10000779.html 小总结 HashMap.Hashtable.ConcurrentHashMap HashM ...
- Java并发(十七):ConcurrentHashMap
先做总结: 1.HashMap HashTable ConcurrentHashMap HashMap:线程不安全 HashTable:线程安全,每个方法都加了 synchronized 修饰.类似 ...
- Java并发包源码分析
并发是一种能并行运行多个程序或并行运行一个程序中多个部分的能力.如果程序中一个耗时的任务能以异步或并行的方式运行,那么整个程序的吞吐量和可交互性将大大改善.现代的PC都有多个CPU或一个CPU中有多个 ...
- HashMap vs ConcurrentHashMap — 示例及Iterator探秘
如果你是一名Java开发人员,我能够确定你肯定知道ConcurrentModificationException,它是在使用迭代器遍历集合对象时修改集合对象造成的(并发修改)异常.实际上,Java的集 ...
- ConcurrentHashMap Put()操作示例代码
非常简练: private static void put(MetricKey key, float value) { MetricValue current; do { current = map. ...
- 【JUC】JDK1.8源码分析之ConcurrentHashMap(一)
一.前言 最近几天忙着做点别的东西,今天终于有时间分析源码了,看源码感觉很爽,并且发现ConcurrentHashMap在JDK1.8版本与之前的版本在并发控制上存在很大的差别,很有必要进行认真的分析 ...
- Java多线程系列--“JUC集合”04之 ConcurrentHashMap
概要 本章是JUC系列的ConcurrentHashMap篇.内容包括:ConcurrentHashMap介绍ConcurrentHashMap原理和数据结构ConcurrentHashMap函数列表 ...
- 从一个简单的Java单例示例谈谈并发
一个简单的单例示例 单例模式可能是大家经常接触和使用的一个设计模式,你可能会这么写 public class UnsafeLazyInitiallization { private static Un ...
- 从一个简单的Java单例示例谈谈并发 JMM JUC
原文: http://www.open-open.com/lib/view/open1462871898428.html 一个简单的单例示例 单例模式可能是大家经常接触和使用的一个设计模式,你可能会这 ...
随机推荐
- ios 录音
http://code4app.com/ios/%E5%BD%95%E9%9F%B3%E5%92%8C%E6%92%AD%E6%94%BE/51ba821b6803fa6901000000
- 为ProgressBar进度条设置颜色1
可以通过xml文件来设置,方法如下: 1:先在布局文件中的ProgressBar加入下面属性: android:progressDrawable="@drawable/progress_ba ...
- C#中gridView常用属性和技巧介绍
.隐藏最上面的GroupPanel gridView1.OptionsView.ShowGroupPanel=false; .得到当前选定记录某字段的值 sValue=Table.Rows[gridV ...
- Linux使用标准IO的调用函数,分3种形式实现
/*根据cp命令的格式要求,设计一个类cp的功能程序,要求使用标准IO的调用函数,分3种形式实现,字符,行,块.并注意函数功能的分层*/ #include<stdio.h> #includ ...
- EHCache 实现通用类 CacheManager
package com.zhubaje.api.workflow.ehcache; import java.io.Serializable; import java.util.ArrayList; i ...
- vim命令总结
前言 本文翻译自:http://bencrowder.net/files/vim-fu/,参考了VIM中文帮助. Google翻译结果和实际操作结果,对原文的部分内容重新整理,删除和添加了 部分内容并 ...
- 【HTML5】websocket 初识
什么是WebSocket API? WebSocket API是下一代客户端-服务器的异步通信方法.该通信取代了单个的TCP套接字,使用ws或wss协议,可用于任意的客户端和服务器程序.WebSock ...
- libreoffice转换文档的方法(支持各平台各版本的libreoffice)
前段时间完成了一个利用libreoffice转换文档进行预览的资源管理系统,用的是jodconvert这个多年未更新的转换项目,由于版本不兼容等原因,导致最新版的libreoffice不能用,浪费了许 ...
- javascript_22_for_js性感的v
<script type="text/javascript"> window.onload=function(){ var aDiv=document.getEleme ...
- Exception in thread "http-bio-8081-exec-3" java.lang.OutOfMemoryError: PermGen space
前言: 在http://www.cnblogs.com/wql025/p/4865673.html一文中我曾描述这种异常也提供了解决方式,但效果不太理想,现在用本文的方式,效果显著. 目前此项目只能登 ...