---
title: "ConcurrentHashMap的弱一致性导致的并发错误"
author: "cloudeagle_bupt"
date: "2016-09-23T00:12:00Z"
tags: []
slug: "concurrenthashmap"
draft: false
lastmod: "2016-11-23T20:43:41Z"
id: 2340181
url: "https://cloudeagle-bupt.iteye.com/blog/2340181"
---

遇到如下异常

```
java.lang.IllegalStateException
	at java.util.concurrent.ConcurrentHashMap$HashIterator.remove(ConcurrentHashMap.java:1366)
	at org.apache.hama.graph.IncomingVertexMessageManager.poll(IncomingVertexMessageManager.java:98)
	at org.apache.hama.graph.IncomingVertexMessageManager.poll(IncomingVertexMessageManager.java:1)
	at org.apache.hama.bsp.message.AbstractMessageManager.getCurrentMessage(AbstractMessageManager.java:122)
	at org.apache.hama.bsp.BSPPeerImpl.getCurrentMessage(BSPPeerImpl.java:365)
	at org.apache.hama.graph.GraphJobRunner.doSuperstep(GraphJobRunner.java:294)
	at org.apache.hama.graph.GraphJobRunner.bsp(GraphJobRunner.java:196)
	at org.apache.hama.bsp.BSPTask.runBSP(BSPTask.java:171)
	at org.apache.hama.bsp.BSPTask.run(BSPTask.java:144)
	at org.apache.hama.bsp.GroomServer$BSPPeerChild.main(GroomServer.java:1255)
```

参考下ConcurrentHashMap的remove实现代码:

```
       public final void remove() {
            if (lastReturned == null)
                throw new IllegalStateException();
            ConcurrentHashMap.this.remove(lastReturned.key);
            lastReturned = null;
        }
```

1\. 简单的说，在HashMap的容器中，其modCount是表示map中的元素被修改了几次(在移除，新加元素时此值都会自增)，而expectedModCount是表示期望的修改次数，在迭代器构造的时候这两个值是相等，如果在遍历过程中这两个值出现了不同步就会抛出ConcurrentModificationException异常。

这是通常HashMap会报的错误。

2.这里IllegalStateException则是因为通常是两个并发线程删除使用了同一个iterator线程,导致线程并发问题。

此外，如果你在遍历中直接删除容器元素也会报类似错误 NoSuchElementException ,IllegalStateException等等。

对于同时增加和删除，是OK的。

但是同时两边删除，则会造成两边遍历的总数据不一致！

参考日志:http://lz12366.iteye.com/blog/675016

https://zhouhualei.github.io/2015/06/08/deep-into-consitency-of-hashmap-and-concurrenthashmap/

http://dumbee.net/archives/41

参考这里:

http://www.cnblogs.com/zhuawang/p/4779649.html

ConcurrentHashMap的简要总结：

1、public V get(Object key)不涉及到锁，也就是说获得对象时没有使用锁；

2、put、remove方法要使用锁，但并不一定有锁争用，原因在于ConcurrentHashMap将缓存的变量分到多个Segment，每个Segment上有一个锁，只要多个线程访问的不是一个Segment就没有锁争用，就没有堵塞，各线程用各自的锁，ConcurrentHashMap缺省情况下生成16个Segment，也就是允许16个线程并发的更新而尽量没有锁争用；

3、Iterator对象的使用，不一定是和其它更新线程同步，获得的对象可能是更新前的对象，ConcurrentHashMap允许一边更新、一边遍历，也就是说在Iterator对象遍历的时候，ConcurrentHashMap也可以进行remove,put操作，且遍历的数据会随着remove,put操作产出变化，所以希望遍历到当前全部数据的话，要么以ConcurrentHashMap变量为锁进行同步(synchronized该变量)，要么使用CopiedIterator包装iterator，使其拷贝当前集合的全部数据，但是这样生成的iterator不可以进行remove操作。

Hashtable和ConcurrentHashMap的不同点：

1、Hashtable对get,put,remove都使用了同步操作，它的同步级别是正对Hashtable来进行同步的，也就是说如果有线程正在遍历集合，其他的线程就暂时不能使用该集合了，这样无疑就很容易对性能和吞吐量造成影响，从而形成单点。而ConcurrentHashMap则不同，它只对put,remove操作使用了同步操作，get操作并不影响，详情请看以上第1,2点，当前ConcurrentHashMap这样的做法对一些线程要求很严格的程序来说，还是有所欠缺的，对应这样的程序来说，如果不考虑性能和吞吐量问题的话，个人觉得使用Hashtable还是比较合适的；

2、Hashtable在使用iterator遍历的时候，如果其他线程，包括本线程对Hashtable进行了put，remove等更新操作的话，就会抛出ConcurrentModificationException异常，但如果使用ConcurrentHashMap的话，就不用考虑这方面的问题了，详情请看以上第3点；

1.HashMap或者ArrayList边遍历边删除数据会报java.util.ConcurrentModificationException异常

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

```
Map<Long, String> mReqPacket = new HashMap<Long, String>();
        for (long i = 0; i < 15; i++) {
            mReqPacket.put(i, i + "");
        }

        for (Entry<Long, String> entry : mReqPacket.entrySet()) {
            long key = entry.getKey();
            String value = entry.getValue();
            if (key < 10) {
                mReqPacket.remove(key);
            }
        }

        for (Entry<Long, String> entry : mReqPacket.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
```

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

所以要用迭代器删除元素：

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

```
        Map<Long, String> mReqPacket = new HashMap<Long, String>();
        for (long i = 0; i < 15; i++) {
            mReqPacket.put(i, i + "");
        }

        for (Iterator<Entry<Long, String>> iterator = mReqPacket.entrySet().iterator(); iterator.hasNext();) {
            Entry<Long, String> entry = iterator.next();
            long key = entry.getKey();
            if (key < 10) {
                iterator.remove();
            }
        }

        for (Entry<Long, String> entry : mReqPacket.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
```

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

2.对ConcurrentHashMap边遍历边删除或者增加操作不会产生异常(可以不用迭代方式删除元素)，因为其内部已经做了维护，遍历的时候都能获得最新的值。即便是多个线程一起删除、添加元素也没问题。

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

```
        Map<Long, String> conMap = new ConcurrentHashMap<Long, String>();
        for (long i = 0; i < 15; i++) {
            conMap.put(i, i + "");
        }

        for (Entry<Long, String> entry : conMap.entrySet()) {
            long key = entry.getKey();
            if (key < 10) {
                conMap.remove(key);
            }
        }

        for (Entry<Long, String> entry : conMap.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }
```

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

3.一个线程对ConcurrentHashMap增加数据，另外一个线程在遍历时就能获得。

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

```
static Map<Long, String> conMap = new ConcurrentHashMap<Long, String>();

    public static void main(String[] args) throws InterruptedException {
        for (long i = 0; i < 5; i++) {
            conMap.put(i, i + "");
        }

        Thread thread = new Thread(new Runnable() {
            public void run() {
                conMap.put(100l, "100");
                System.out.println("ADD:" + 100);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        });
        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                for (Iterator<Entry<Long, String>> iterator = conMap.entrySet().iterator(); iterator.hasNext();) {
                    Entry<Long, String> entry = iterator.next();
                    System.out.println(entry.getKey() + " - " + entry.getValue());
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
        thread2.start();

        Thread.sleep(3000);
        System.out.println("--------");
        for (Entry<Long, String> entry : conMap.entrySet()) {
            System.out.println(entry.getKey() + " " + entry.getValue());
        }

    }

输出：
```

ADD:100  
0 - 0  
100 - 100  
2 - 2  
1 - 1  
3 - 3  
4 - 4  
\--------  
0 0  
100 100  
2 2  
1 1  
3 3  
4 4

```

```

[![复制代码](http://common.cnblogs.com/images/copycode.gif)]()

其中，他说多个线程同时对concurrentHashmap进行删除操作没有问题，这点令我很奇怪。。。。 先记着吧