为什么阿里巴巴强制不要在 Foreach 里执行删除操作

开发 前端
很多时候,我们会把 fail-fast 归类为 Java 集合框架的一种错误检测机制,但其实 fail-fast 并不是 Java 集合框架特有的机制。

[[430039]]

为了镇楼,先搬一段英文来解释一下 fail-fast。

In systems design, a fail-fast system is one which immediately reports at its interface any condition that is likely to indicate a failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly flawed process. Such designs often check the system's state at several points in an operation, so any failures can be detected early. The responsibility of a fail-fast module is detecting errors, then letting the next-highest level of the system handle them.

这段话的大致意思就是,fail-fast 是一种通用的系统设计思想,一旦检测到可能会发生错误,就立马抛出异常,程序将不再往下执行。

  1. public void test(Wanger wanger) {    
  2.     if (wanger == null) { 
  3.         throw new RuntimeException("wanger 不能为空"); 
  4.     } 
  5.      
  6.     System.out.println(wanger.toString()); 

一旦检测到 wanger 为 null,就立马抛出异常,让调用者来决定这种情况下该怎么处理,下一步 wanger.toString() 就不会执行了——避免更严重的错误出现。

很多时候,我们会把 fail-fast 归类为 Java 集合框架的一种错误检测机制,但其实 fail-fast 并不是 Java 集合框架特有的机制。

之所以我们把 fail-fast 放在集合框架篇里介绍,是因为问题比较容易再现。

  1. List<String> list = new ArrayList<>(); 
  2. list.add("沉默王二"); 
  3. list.add("沉默王三"); 
  4. list.add("一个文章真特么有趣的程序员"); 
  5.  
  6. for (String str : list) { 
  7.  if ("沉默王二".equals(str)) { 
  8.   list.remove(str); 
  9.  } 
  10.  
  11. System.out.println(list); 

这段代码看起来没有任何问题,但运行起来就报错了。

根据错误的堆栈信息,我们可以定位到 ArrayList 的第 901 行代码。

  1. final void checkForComodification() { 
  2.     if (modCount != expectedModCount) 
  3.         throw new ConcurrentModificationException(); 

也就是说,remove 的时候触发执行了 checkForComodification 方法,该方法对 modCount 和 expectedModCount 进行了比较,发现两者不等,就抛出了 ConcurrentModificationException 异常。

为什么会执行 checkForComodification 方法呢?

是因为 for-each 本质上是个语法糖,底层是通过迭代器 Iterator 配合 while 循环实现的,来看一下反编译后的字节码。

  1. List<String> list = new ArrayList(); 
  2. list.add("沉默王二"); 
  3. list.add("沉默王三"); 
  4. list.add("一个文章真特么有趣的程序员"); 
  5. Iterator var2 = list.iterator(); 
  6.  
  7. while(var2.hasNext()) { 
  8.     String str = (String)var2.next(); 
  9.     if ("沉默王二".equals(str)) { 
  10.         list.remove(str); 
  11.     } 
  12.  
  13. System.out.println(list); 

来看一下 ArrayList 的 iterator 方法吧:

  1. public Iterator<E> iterator() { 
  2.     return new Itr(); 

内部类 Itr 实现了 Iterator 接口。

  1. private class Itr implements Iterator<E> { 
  2.     int cursor;       // index of next element to return 
  3.     int lastRet = -1; // index of last element returned; -1 if no such 
  4.     int expectedModCount = modCount; 
  5.  
  6.     Itr() {} 
  7.  
  8.     public boolean hasNext() { 
  9.         return cursor != size
  10.     } 
  11.  
  12.     @SuppressWarnings("unchecked"
  13.     public E next() { 
  14.         checkForComodification(); 
  15.         int i = cursor
  16.         Object[] elementData = ArrayList.this.elementData; 
  17.         if (i >= elementData.length) 
  18.             throw new ConcurrentModificationException(); 
  19.         cursor = i + 1; 
  20.         return (E) elementData[lastRet = i]; 
  21.     } 

也就是说 new Itr() 的时候 expectedModCount 被赋值为 modCount,而 modCount 是 List 的一个成员变量,表示集合被修改的次数。由于 list 此前执行了 3 次 add 方法。

  • add 方法调用 ensureCapacityInternal 方法
  • ensureCapacityInternal 方法调用 ensureExplicitCapacity 方法
  • ensureExplicitCapacity 方法中会执行 modCount++

所以 modCount 的值在经过三次 add 后为 3,于是 new Itr() 后 expectedModCount 的值也为 3。

执行第一次循环时,发现“沉默王二”等于 str,于是执行 list.remove(str)。

  • remove 方法调用 fastRemove 方法
  • fastRemove 方法中会执行 modCount++
  1. private void fastRemove(int index) { 
  2.     modCount++; 
  3.     int numMoved = size - index - 1; 
  4.     if (numMoved > 0) 
  5.         System.arraycopy(elementData, index+1, elementData, index
  6.                          numMoved); 
  7.     elementData[--size] = null; // clear to let GC do its work 

modCount 的值变成了 4。

执行第二次循环时,会执行 Itr 的 next 方法(String str = (String) var3.next();),next 方法就会调用 checkForComodification 方法,此时 expectedModCount 为 3,modCount 为 4,就只好抛出 ConcurrentModificationException 异常了。

那其实在阿里巴巴的 Java 开发手册里也提到了,不要在 for-each 循环里进行元素的 remove/add 操作。remove 元素请使用 Iterator 方式。

那原因其实就是我们上面分析的这些,出于 fail-fast 保护机制。

那该如何正确地删除元素呢?

1)remove 后 break

  1. List<String> list = new ArrayList<>(); 
  2. list.add("沉默王二"); 
  3. list.add("沉默王三"); 
  4. list.add("一个文章真特么有趣的程序员"); 
  5.  
  6. for (String str : list) { 
  7.  if ("沉默王二".equals(str)) { 
  8.   list.remove(str); 
  9.   break; 
  10.  } 

break 后循环就不再遍历了,意味着 Iterator 的 next 方法不再执行了,也就意味着 checkForComodification 方法不再执行了,所以异常也就不会抛出了。

但是呢,当 List 中有重复元素要删除的时候,break 就不合适了。

2)for 循环

  1. List<String> list = new ArrayList<>(); 
  2. list.add("沉默王二"); 
  3. list.add("沉默王三"); 
  4. list.add("一个文章真特么有趣的程序员"); 
  5. for (int i = 0, n = list.size(); i < n; i++) { 
  6.  String str = list.get(i); 
  7.  if ("沉默王二".equals(str)) { 
  8.   list.remove(str); 
  9.  } 

for 循环虽然可以避开 fail-fast 保护机制,也就说 remove 元素后不再抛出异常;但是呢,这段程序在原则上是有问题的。为什么呢?

第一次循环的时候,i 为 0,list.size() 为 3,当执行完 remove 方法后,i 为 1,list.size() 却变成了 2,因为 list 的大小在 remove 后发生了变化,也就意味着“沉默王三”这个元素被跳过了。能明白吗?

remove 之前 list.get(1) 为“沉默王三”;但 remove 之后 list.get(1) 变成了“一个文章真特么有趣的程序员”,而 list.get(0) 变成了“沉默王三”。

3)使用 Iterator

  1. List<String> list = new ArrayList<>(); 
  2. list.add("沉默王二"); 
  3. list.add("沉默王三"); 
  4. list.add("一个文章真特么有趣的程序员"); 
  5.  
  6. Iterator<String> itr = list.iterator(); 
  7.  
  8. while (itr.hasNext()) { 
  9.  String str = itr.next(); 
  10.  if ("沉默王二".equals(str)) { 
  11.   itr.remove(); 
  12.  } 

为什么使用 Iterator 的 remove 方法就可以避开 fail-fast 保护机制呢?看一下 remove 的源码就明白了。

  1. public void remove() { 
  2.     if (lastRet < 0) 
  3.         throw new IllegalStateException(); 
  4.     checkForComodification(); 
  5.  
  6.     try { 
  7.         ArrayList.this.remove(lastRet); 
  8.         cursor = lastRet; 
  9.         lastRet = -1; 
  10.         expectedModCount = modCount; 
  11.     } catch (IndexOutOfBoundsException ex) { 
  12.         throw new ConcurrentModificationException(); 
  13.     } 

删除完会执行 expectedModCount = modCount,保证了 expectedModCount 与 modCount 的同步。

简单地总结一下,fail-fast 是一种保护机制,可以通过 for-each 循环删除集合的元素的方式验证这种保护机制。 

那也就是说,for-each 本质上是一种语法糖,遍历集合时很方面,但并不适合拿来操作集合中的元素(增删)。

本文转载自微信公众号「沉默王二」,可以通过以下二维码关注。转载本文请联系沉默王二公众号。

 

责任编辑:武晓燕 来源: 沉默王二
相关推荐

2023-04-03 07:03:51

阿里巴巴List元素

2019-03-04 09:22:52

阿里巴巴foreach Java

2021-10-11 09:32:40

包装类型属性

2018-10-16 15:34:17

阿里巴巴Apache Flin大数据

2013-08-22 09:26:38

去IOE王坚

2016-09-21 20:28:55

阿里巴巴IOE

2021-08-04 17:20:30

阿里巴巴AsyncJava

2019-09-04 11:02:54

继承层次组合

2020-09-14 09:47:56

Java开发类型

2019-09-02 15:20:28

Java开发继承

2021-09-07 17:22:43

阿里巴巴辞职高薪

2020-09-08 16:25:18

Apache BeancopyJava

2022-09-05 10:06:21

MySQL外循环内循环

2010-06-28 10:43:47

2020-07-30 12:16:33

阿里巴巴Apache对象

2019-06-26 07:54:53

ArrayListsubList源码

2020-09-22 11:40:53

BigDecimalequalsJava

2013-08-22 09:41:52

阿里巴巴去IOE王坚

2012-09-17 10:20:11

2019-04-15 08:49:59

阿里巴巴容量集合
点赞
收藏

51CTO技术栈公众号