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。