那天,小二去阿裡面試,面試官老王一上來就甩給了他一道面試題:為什麼阿裡的 Java 開發手冊裡會強制不要在 foreach 裡進行元素的删除操作?小二聽完就面露喜色,因為兩年前,也就是 2021 年,他在《Java 程式員進階之路》專欄上的第 63 篇看到過這題😆。
PS:star 這種事,隻能求,不求沒效果,鐵子們,《Java 程式員進階之路》在 GitHub 上已經收獲了 523 枚星标,小夥伴們趕緊去點點了,沖 600 star!
https://github.com/itwanger/toBeBetterJavaer為了鎮樓,先搬一段英文來解釋一下 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 是一種通用的系統設計思想,一旦檢測到可能會發生錯誤,就立馬抛出異常,程式将不再往下執行。
public void test(Wanger wanger) {
if (wanger == null) {
throw new RuntimeException("wanger 不能為空");
}
System.out.println(wanger.toString());
}
一旦檢測到 wanger 為 null,就立馬抛出異常,讓調用者來決定這種情況下該怎麼處理,下一步 wanger.toString() 就不會執行了——避免更嚴重的錯誤出現。
很多時候,我們會把 fail-fast 歸類為 Java 集合架構的一種錯誤檢測機制,但其實 fail-fast 并不是 Java 集合架構特有的機制。
之是以我們把 fail-fast 放在集合架構篇裡介紹,是因為問題比較容易再現。
List<String> list = new ArrayList<>();
list.add("沉默王二");
list.add("沉默王三");
list.add("一個文章真特麼有趣的程式員");
for (String str : list) {
if ("沉默王二".equals(str)) {
list.remove(str);
}
}
System.out.println(list);
這段代碼看起來沒有任何問題,但運作起來就報錯了。
根據錯誤的堆棧資訊,我們可以定位到 ArrayList 的第 901 行代碼。
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
也就是說,remove 的時候觸發執行了 checkForComodification 方法,該方法對 modCount 和 expectedModCount 進行了比較,發現兩者不等,就抛出了 ConcurrentModificationException 異常。
為什麼會執行 checkForComodification 方法呢?
是因為 for-each 本質上是個文法糖,底層是通過疊代器 Iterator 配合 while 循環實作的,來看一下反編譯後的位元組碼。
List<String> list = new ArrayList();
list.add("沉默王二");
list.add("沉默王三");
list.add("一個文章真特麼有趣的程式員");
Iterator var2 = list.iterator();
while(var2.hasNext()) {
String str = (String)var2.next();
if ("沉默王二".equals(str)) {
list.remove(str);
}
}
System.out.println(list);
來看一下 ArrayList 的 iterator 方法吧:
public Iterator<E> iterator() {
return new Itr();
}
内部類 Itr 實作了 Iterator 接口。
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
}
也就是說 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++
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
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
List<String> list = new ArrayList<>();
list.add("沉默王二");
list.add("沉默王三");
list.add("一個文章真特麼有趣的程式員");
for (String str : list) {
if ("沉默王二".equals(str)) {
list.remove(str);
break;
}
}
break 後循環就不再周遊了,意味着 Iterator 的 next 方法不再執行了,也就意味着 checkForComodification 方法不再執行了,是以異常也就不會抛出了。
但是呢,當 List 中有重複元素要删除的時候,break 就不合适了。
2)for 循環
List<String> list = new ArrayList<>();
list.add("沉默王二");
list.add("沉默王三");
list.add("一個文章真特麼有趣的程式員");
for (int i = 0, n = list.size(); i < n; i++) {
String str = list.get(i);
if ("沉默王二".equals(str)) {
list.remove(str);
}
}
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
List<String> list = new ArrayList<>();
list.add("沉默王二");
list.add("沉默王三");
list.add("一個文章真特麼有趣的程式員");
Iterator<String> itr = list.iterator();
while (itr.hasNext()) {
String str = itr.next();
if ("沉默王二".equals(str)) {
itr.remove();
}
}
為什麼使用 Iterator 的 remove 方法就可以避開 fail-fast 保護機制呢?看一下 remove 的源碼就明白了。
public void remove() {
if (lastRet < 0)
throw new IllegalStateException();
checkForComodification();
try {
ArrayList.this.remove(lastRet);
cursor = lastRet;
lastRet = -1;
expectedModCount = modCount;
} catch (IndexOutOfBoundsException ex) {
throw new ConcurrentModificationException();
}
}
删除完會執行 expectedModCount = modCount,保證了 expectedModCount 與 modCount 的同步。
簡單地總結一下,fail-fast 是一種保護機制,可以通過 for-each 循環删除集合的元素的方式驗證這種保護機制。
那也就是說,for-each 本質上是一種文法糖,周遊集合時很方面,但并不适合拿來操作集合中的元素(增删)。
這是《Java 程式員進階之路》專欄的第 63 篇。Java 程式員進階之路,風趣幽默、通俗易懂,對 Java 初學者極度友好和舒适😘,内容包括但不限于 Java 文法、Java 集合架構、Java IO、Java 并發程式設計、Java 虛拟機等核心知識點。
亮白版和暗黑版的 PDF 也準備好了呢,一起成為更好的 Java 工程師,沖!