HashMap的线程不安全是在说什么
Java程序员都曾被问到的一个问题是: 为什么HashMap是线程不安全的? 为什么ConcurrentHashMap是线程安全的? 为什么HashMap是线程不安全的? Fail-Fast 机制 如果在使用迭代器的过程中有其他线程修改了map,那么将抛出ConcurrentModificationException,这就是所谓fail-fast策略。 看源码的时候我们会看到,在ArrayList,LinkedList,HashMap的内部,有一个int类型的modCount对象,对上述集合内容的修改都将增加这个值。modCount会在迭代器Iterator中使用,在迭代器的构造函数中,有这么一行代码,expectedModCount = modCount。在nextEntity和remove方法的调用过程中,如果modCount != expectedModCount,抛出ConcurrentModificationException异常。 final Entry < K , V > nextEntry ( ) { if ( modCount != expectedModCount ) throw new ConcurrentModificationException ( ) ; } public void remove ( ) { if ( modCount !=