> 文章列表 > Fail-Fast机制和ConcurrentModificationException并发修改异常

Fail-Fast机制和ConcurrentModificationException并发修改异常

Fail-Fast机制和ConcurrentModificationException并发修改异常

目录

    • 说明
    • Fail-Fast机制
      • Fail-Fast机制的理解
      • 如何解决Fail-Fast错误机制的问题

说明

  Fail-Fast机制和ConcurrentModificationException并发修改异常是我们在编写代码的时候经常遇到的问题和异常,我们需要搞清楚这个机制是什么东西并且为什么会抛出这个异常,如何进行解决。
 
 

Fail-Fast机制

  Fail-Fast机制是Java集合框架中的一种错误机制,当多个线程对一个不安全的集合进行操作时,就可能会出现fail-fast机制。
  我们来举个例子:当我们的线程A正在使用iterator去遍历一个ArrayList或者是HashMap的时候,另一个线程B在线程A遍历的时候对该List或者Map进行add、delete、clear,这个时候线程A就很可能会抛出ConcurrentModificationException并发修改异常,产生fail-fast错误机制。
 

Fail-Fast机制的理解

  我们可以这样理解Fail-Fast机制,在集合遍历之前,我们先把集合的size,也就是modCount记录下来,在集合遍历之后产生的expectModCount,我们将modCount和expectModCount进行比较,如果不相等,那么就抛出ConcurrentModificationException并发修改异常,产生fail-fast错误机制。

 

如何解决Fail-Fast错误机制的问题

  在高并发的情况下,建议使用“java.util.concurrent”包下的类去代替“java.util”包下的类,一般我们使用List会使用到ArrayList,使用Map会使用HashMap。

ArrayList

List<Integer> list = new ArrayList<>();list.add(1);list.add(2);list.add(3);Iterator<Integer> iterator = list.iterator();while (iterator.hasNext()) {Integer next = iterator.next();if (next.equals(1)) {list.remove(1);}}

Fail-Fast机制和ConcurrentModificationException并发修改异常

 
 
HashMap

            Map<Integer,Integer> map = new HashMap<>();map.put(1,1);map.put(2,1);map.put(3,1);Set<Map.Entry<Integer, Integer>> entries = map.entrySet();for (Map.Entry<Integer, Integer> entry : entries) {if (entry.getKey() == 2) {map.remove(2);}}

Fail-Fast机制和ConcurrentModificationException并发修改异常
解决方案:

  • 我们使用CopyOnWriteArrayList----来代替ArrayList。
  • 我们使用ConcurrentHashMap----来代替HashMap。