concurrent复合操作问题

ConcurrentHashMap通常只被看做并发效率更高的Map,用来替换其他线程安全的Map容器,比如Hashtable和Collections.synchronizedMap。实际上,线程安全的容器,特别是Map,应用场景没有想象中的多,很多情况下一个业务会涉及容器的多个操作,即复合操作,并发执行时,线程安全的容器只能保证自身的数据不被破坏,但无法保证业务的行为是否正确。

举个例子:统计文本中单词出现的次数,把单词出现的次数记录到一个Map中,代码如下:

[java]  view plain  copy
 print ?
  1. private final Map<String, Long> wordCounts = new ConcurrentHashMap<>();  
  2.   
  3. public long increase(String word) {  
  4.     Long oldValue = wordCounts.get(word);  
  5.     Long newValue = (oldValue == null) ? 1L : oldValue + 1;  
  6.     wordCounts.put(word, newValue);  
  7.     return newValue;  
  8. }  


如果多个线程并发调用这个increase()方法,increase()的实现就是错误的,因为多个线程用相同的word调用时,很可能会覆盖相互的结果,造成记录的次数比实际出现的次数少。
除了用锁解决这个问题,另外一个选择是使用ConcurrentMap接口定义的方法:

[java]  view plain  copy
 print ?
  1. public interface ConcurrentMap<K, V> extends Map<K, V> {  
  2.     V putIfAbsent(K key, V value);  
  3.     boolean remove(Object key, Object value);  
  4.     boolean replace(K key, V oldValue, V newValue);  
  5.     V replace(K key, V value);  
  6. }  


这是个被很多人忽略的接口,也经常见有人错误地使用这个接口。ConcurrentMap接口定义了几个基于 CAS(Compare and Set)操作,很简单,但非常有用,下面的代码用ConcurrentMap解决上面问题:

[java]  view plain  copy
 print ?
  1. private final ConcurrentMap<String, Long> wordCounts = new ConcurrentHashMap<>();  
  2.   
  3. public long increase(String word) {  
  4.     Long oldValue, newValue;  
  5.     while (true) {  
  6.         oldValue = wordCounts.get(word);  
  7.         if (oldValue == null) {  
  8.             // Add the word firstly, initial the value as 1  
  9.             newValue = 1L;  
  10.             if (wordCounts.putIfAbsent(word, newValue) == null) {  
  11.                 break;  
  12.             }  
  13.         } else {  
  14.             newValue = oldValue + 1;  
  15.             if (wordCounts.replace(word, oldValue, newValue)) {  
  16.                 break;  
  17.             }  
  18.         }  
  19.     }  
  20.     return newValue;  
  21. }  


代码有点复杂,主要因为ConcurrentMap中不能保存value为null的值,所以得同时处理word不存在和已存在两种情况。

上面的实现每次调用都会涉及Long对象的拆箱和装箱操作,很明显,更好的实现方式是采用AtomicLong,下面是采用AtomicLong后的代码:

[java]  view plain  copy
 print ?
  1. private final ConcurrentMap<String, AtomicLong> wordCounts = new ConcurrentHashMap<>();  
  2.   
  3. public long increase(String word) {  
  4.     AtomicLong number = wordCounts.get(word);  
  5.     if (number == null) {  
  6.         AtomicLong newNumber = new AtomicLong(0);  
  7.         number = wordCounts.putIfAbsent(word, newNumber);  
  8.         if (number == null) {  
  9.             number = newNumber;  
  10.         }  
  11.     }  
  12.     return number.incrementAndGet();  
  13. }  


这个实现仍然有一处需要说明的地方,如果多个线程同时增加一个目前还不存在的词,那么很可能会产生多个newNumber对象,但最终只有一个newNumber有用,其他的都会被扔掉。对于这个应用,这不算问题,创建AtomicLong的成本不高,而且只在添加不存在词是出现。但换个场景,比如缓存,那么这很可能就是问题了,因为缓存中的对象获取成本一般都比较高,而且通常缓存都会经常失效,那么避免重复创建对象就有价值了。下面的代码演示了怎么处理这种情况:

[java]  view plain  copy
 print ?
  1. private final ConcurrentMap<String, Future<ExpensiveObj>> cache = new ConcurrentHashMap<>();  
  2.   
  3. public ExpensiveObj get(final String key) {  
  4.     Future<ExpensiveObj> future = cache.get(key);  
  5.     if (future == null) {  
  6.         Callable<ExpensiveObj> callable = new Callable<ExpensiveObj>() {  
  7.             @Override  
  8.             public ExpensiveObj call() throws Exception {  
  9.                 return new ExpensiveObj(key);  
  10.             }  
  11.         };  
  12.         FutureTask<ExpensiveObj> task = new FutureTask<>(callable);  
  13.   
  14.         future = cache.putIfAbsent(key, task);  
  15.         if (future == null) {  
  16.             future = task;  
  17.             task.run();  
  18.         }  
  19.     }  
  20.   
  21.     try {  
  22.         return future.get();  
  23.     } catch (Exception e) {  
  24.         cache.remove(key);  
  25.         throw new RuntimeException(e);  
  26.     }  
  27. }  


解决方法其实就是用一个Proxy对象来包装真正的对象,跟常见的lazy load原理类似;使用FutureTask主要是为了保证同步,避免一个Proxy创建多个对象。注意,上面代码里的异常处理是不准确的。

最后再补充一下,如果真要实现前面说的统计单词次数功能,最合适的方法是Guava包中AtomicLongMap;一般使用ConcurrentHashMap,也尽量使用Guava中的MapMaker或cache实现。


AtomicLongMap是Google Guava项目的一个类,它是线程安全、支持并发访问的。

Guava 是一个 Google 的基于java1.6的类库集合的扩展项目,包括 collections, caching, primitives support, concurrency libraries, common annotations, string processing, I/O, 等等

[java]  view plain  copy
 print ?
  1. public class GuavaTest {  
  2.     //来自于Google的Guava项目  
  3.     AtomicLongMap<String> map = AtomicLongMap.create(); //线程安全,支持并发  
  4.   
  5.     Map<String, Integer> map2 = new HashMap<String, Integer>(); //线程不安全  
  6.     ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); //为map2增加并发锁  
  7.   
  8.     ConcurrentHashMap<String, Integer> map3 = new ConcurrentHashMap<String, Integer>(); //线程安全,但也要注意使用方式  
  9.   
  10.     private int taskCount = 100;  
  11.     CountDownLatch latch = new CountDownLatch(taskCount); //新建倒计时计数器,设置state为taskCount变量值  
  12.   
  13.     public static void main(String[] args) {  
  14.         GuavaTest t = new GuavaTest();  
  15.         t.test();  
  16.     }  
  17.   
  18.     private void test(){  
  19.         //启动线程  
  20.         for(int i=1; i<=taskCount; i++){  
  21.             Thread t = new Thread(new MyTask("key"100));  
  22.             t.start();  
  23.         }  
  24.   
  25.         try {  
  26.             //等待直到state值为0,再继续往下执行  
  27.             latch.await();  
  28.         } catch (InterruptedException e) {  
  29.             e.printStackTrace();  
  30.         }  
  31.   
  32.         System.out.println("##### AtomicLongMap #####");  
  33.         for(String key : map.asMap().keySet()){  
  34.             System.out.println(key + ": " + map.get(key));  
  35.         }  
  36.   
  37.         System.out.println("##### HashMap #####");  
  38.         for(String key : map2.keySet()){  
  39.             System.out.println(key + ": " + map2.get(key));  
  40.         }  
  41.   
  42.         System.out.println("##### ConcurrentHashMap #####");  
  43.         for(String key : map3.keySet()){  
  44.             System.out.println(key + ": " + map3.get(key));  
  45.         }  
  46.     }  
  47.   
  48.     class MyTask implements Runnable{  
  49.         private String key;  
  50.         private int count = 0;  
  51.   
  52.         public MyTask(String key, int count){  
  53.             this.key = key;  
  54.             this.count = count;  
  55.         }  
  56.   
  57.         @Override  
  58.         public void run() {  
  59.             try {  
  60.                 for(int i=0; i<count; i++){  
  61.                     map.incrementAndGet(key); //key值自增1后,返回该key的值  
  62.   
  63.                     //对map2添加写锁,可以解决线程并发问题  
  64.                     lock.writeLock().lock();  
  65.                     try{  
  66.                         if(map2.containsKey(key)){  
  67.                             map2.put(key, map2.get(key)+1);  
  68.                         }else{  
  69.                             map2.put(key, 1);  
  70.                         }  
  71.                     }catch(Exception ex){  
  72.                         ex.printStackTrace();  
  73.                     }finally{  
  74.                         lock.writeLock().unlock();  
  75.                     }  
  76.   
  77.                     //虽然ConcurrentHashMap是线程安全的,但是以下语句块不是整体同步,导致ConcurrentHashMap的使用存在并发问题  
  78.                     if(map3.containsKey(key)){  
  79.                         map3.put(key, map3.get(key)+1);  
  80.                     }else{  
  81.                         map3.put(key, 1);  
  82.                     }  
  83.   
  84.                     //TimeUnit.MILLISECONDS.sleep(50); //线程休眠50毫秒  
  85.                 }  
  86.   
  87.             } catch (Exception e) {  
  88.                 e.printStackTrace();  
  89.             } finally {  
  90.                 latch.countDown(); //state值减1  
  91.             }  
  92.         }  
  93.     }  
  94.   
  95. }  



执行结果如下:

AtomicLongMap

key: 10000

HashMap

key: 10000

ConcurrentHashMap

key: 9311
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值