HashMap的并发问题

先上一段代码

public class CurrMap {

    /** 线程池 */

    private static final Executor EXECUTOR = Executors.newFixedThreadPool(20);

    /**
     * 
     * @param args
     */
    public static void main(String[] args) {

        //      final  Map<String, String> map = new ConcurrentHashMap<String, String>();
        final Map<String, String> map = new HashMap<String, String>();
        map.put("laotu", "handsome");
        final Random random = new Random();

        while (true) {

            EXECUTOR.execute(new Runnable() {
                public void run() {

                    for (int i = 0; i < 1000; i++) {
                        try {
                            TimeUnit.MILLISECONDS.sleep(1);
                        } catch (InterruptedException ex) {
                            System.err.println("t5 catch the InterruptedException...");
                        }
                        for (String key : map.keySet()) {
                        }
                    }

                }
            });

            for (int i = 0; i < 100; i++) {

                EXECUTOR.execute(new Runnable() {

                    public void run() {

                        for (int i = 0; i < 1000; i++) {
                            try {
                                TimeUnit.MILLISECONDS.sleep(1);
                            } catch (InterruptedException ex) {
                                System.err.println("t1 catch the InterruptedException...");
                            }
                            int key = random.nextInt(1000);
                            map.put(String.valueOf(key), String.valueOf(key));
                        }
                    }

                });

            }
        }

    }

}

执行结果:

Exception in thread "pool-1-thread-1" java.util.ConcurrentModificationException
	at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
	at java.util.HashMap$KeyIterator.next(HashMap.java:828)
	at com.alipay.ctu.biz.intl.filters.CurrMap$1.run(CurrMap.java:52)
	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
	at java.lang.Thread.run(Thread.java:695)


尝试以下两种方案:

a. 把HashMap更换为ConcurrentHashMap,然后执行.

b. 仍使用HashMap, 注释掉第一段EXECUTOR.execute 的代码,然后执行。

结果呢:

方案a肯定不会报这个错。方案b应该不会报这个错,但是存在极小的可能会报这个错。


应用场景:

一笔交易支付事件过来,事件类型为HashMap,我们需要对卡信息,IP信息等进行信息补全,通过线程池并发执行信息补全的过程中,在每个线程内部执行了map.put(key,value)的操作,因此在高并发情况下会可能会抛出异常java.util.ConcurrentModificationException。(出现概率低)

如果此时在线程中执行map.keySet() 操作,遍历map中的数据,那么出现异常java.util.ConcurrentModificationException的概率就很高了。


如果使用HashMap,我们已经清楚不是线程安全的了,那么可能会出现什么问题呢?

a. put 的数据丢失。

b. remove 的数据未被清除,仍然存在。

c. HashMap resize 导致存在性能问题。

d. get 数据时出现死循环。


解决方案:

推荐使用ConcurrentHashMap。


那么是什么原因导致的呢?

可以参照以下两篇文章

http://www.iteye.com/topic/656670
http://www.iteye.com/topic/962172




  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值