那天忧侧,小二去阿里面試,面試官老王一上來(lái)就甩給了他一道面試題:為什么阿里的 Java 開發(fā)手冊(cè)里會(huì)強(qiáng)制不要在 foreach 里進(jìn)行元素的刪除操作挣菲?小二聽完就面露喜色贮喧,因?yàn)閮赡昵埃簿褪?2021 年舔庶,他在《Java 程序員進(jìn)階之路》專欄上的第 63 篇看到過(guò)這題??抛蚁。
PS:star 這種事,只能求惕橙,不求沒效果瞧甩,鐵子們,《Java 程序員進(jìn)階之路》在 GitHub 上已經(jīng)收獲了 417 枚星標(biāo)弥鹦,小伙伴們趕緊去點(diǎn)點(diǎn)了肚逸,沖 500 star!
為了鎮(zhèn)樓彬坏,先搬一段英文來(lái)解釋一下 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 是一種通用的系統(tǒng)設(shè)計(jì)思想栓始,一旦檢測(cè)到可能會(huì)發(fā)生錯(cuò)誤务冕,就立馬拋出異常,程序?qū)⒉辉偻聢?zhí)行幻赚。
public void test(Wanger wanger) {
if (wanger == null) {
throw new RuntimeException("wanger 不能為空");
}
System.out.println(wanger.toString());
}
一旦檢測(cè)到 wanger 為 null禀忆,就立馬拋出異常,讓調(diào)用者來(lái)決定這種情況下該怎么處理坯屿,下一步 wanger.toString()
就不會(huì)執(zhí)行了——避免更嚴(yán)重的錯(cuò)誤出現(xiàn)油湖。
很多時(shí)候,我們會(huì)把 fail-fast 歸類為 Java 集合框架的一種錯(cuò)誤檢測(cè)機(jī)制领跛,但其實(shí) fail-fast 并不是 Java 集合框架特有的機(jī)制乏德。
之所以我們把 fail-fast 放在集合框架篇里介紹,是因?yàn)閱?wèn)題比較容易再現(xiàn)吠昭。
List<String> list = new ArrayList<>();
list.add("沉默王二");
list.add("沉默王三");
list.add("一個(gè)文章真特么有趣的程序員");
for (String str : list) {
if ("沉默王二".equals(str)) {
list.remove(str);
}
}
System.out.println(list);
這段代碼看起來(lái)沒有任何問(wèn)題喊括,但運(yùn)行起來(lái)就報(bào)錯(cuò)了。
根據(jù)錯(cuò)誤的堆棧信息矢棚,我們可以定位到 ArrayList 的第 901 行代碼郑什。
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
也就是說(shuō),remove 的時(shí)候觸發(fā)執(zhí)行了 checkForComodification
方法蒲肋,該方法對(duì) modCount 和 expectedModCount 進(jìn)行了比較蘑拯,發(fā)現(xiàn)兩者不等钝满,就拋出了 ConcurrentModificationException
異常。
為什么會(huì)執(zhí)行 checkForComodification
方法呢申窘?
是因?yàn)?for-each 本質(zhì)上是個(gè)語(yǔ)法糖弯蚜,底層是通過(guò)迭代器 Iterator 配合 while 循環(huán)實(shí)現(xiàn)的,來(lái)看一下反編譯后的字節(jié)碼剃法。
List<String> list = new ArrayList();
list.add("沉默王二");
list.add("沉默王三");
list.add("一個(gè)文章真特么有趣的程序員");
Iterator var2 = list.iterator();
while(var2.hasNext()) {
String str = (String)var2.next();
if ("沉默王二".equals(str)) {
list.remove(str);
}
}
System.out.println(list);
來(lái)看一下 ArrayList 的 iterator 方法吧:
public Iterator<E> iterator() {
return new Itr();
}
內(nèi)部類 Itr 實(shí)現(xiàn)了 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];
}
}
也就是說(shuō) new Itr()
的時(shí)候 expectedModCount 被賦值為 modCount,而 modCount 是 List 的一個(gè)成員變量贷洲,表示集合被修改的次數(shù)收厨。由于 list 此前執(zhí)行了 3 次 add 方法。
- add 方法調(diào)用 ensureCapacityInternal 方法
- ensureCapacityInternal 方法調(diào)用 ensureExplicitCapacity 方法
- ensureExplicitCapacity 方法中會(huì)執(zhí)行
modCount++
所以 modCount 的值在經(jīng)過(guò)三次 add 后為 3优构,于是 new Itr()
后 expectedModCount 的值也為 3诵叁。
執(zhí)行第一次循環(huán)時(shí),發(fā)現(xiàn)“沉默王二”等于 str俩块,于是執(zhí)行 list.remove(str)
黎休。
- remove 方法調(diào)用 fastRemove 方法
- fastRemove 方法中會(huì)執(zhí)行
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浓领。
執(zhí)行第二次循環(huán)時(shí)玉凯,會(huì)執(zhí)行 Itr 的 next 方法(String str = (String) var3.next();
),next 方法就會(huì)調(diào)用 checkForComodification
方法联贩,此時(shí) expectedModCount 為 3漫仆,modCount 為 4,就只好拋出 ConcurrentModificationException 異常了泪幌。
那其實(shí)在阿里巴巴的 Java 開發(fā)手冊(cè)里也提到了盲厌,不要在 for-each 循環(huán)里進(jìn)行元素的 remove/add 操作。remove 元素請(qǐng)使用 Iterator 方式祸泪。
那原因其實(shí)就是我們上面分析的這些吗浩,出于 fail-fast 保護(hù)機(jī)制。
那該如何正確地刪除元素呢没隘?
1)remove 后 break
List<String> list = new ArrayList<>();
list.add("沉默王二");
list.add("沉默王三");
list.add("一個(gè)文章真特么有趣的程序員");
for (String str : list) {
if ("沉默王二".equals(str)) {
list.remove(str);
break;
}
}
break 后循環(huán)就不再遍歷了懂扼,意味著 Iterator 的 next 方法不再執(zhí)行了,也就意味著 checkForComodification
方法不再執(zhí)行了右蒲,所以異常也就不會(huì)拋出了阀湿。
但是呢,當(dāng) List 中有重復(fù)元素要?jiǎng)h除的時(shí)候瑰妄,break 就不合適了陷嘴。
2)for 循環(huán)
List<String> list = new ArrayList<>();
list.add("沉默王二");
list.add("沉默王三");
list.add("一個(gè)文章真特么有趣的程序員");
for (int i = 0, n = list.size(); i < n; i++) {
String str = list.get(i);
if ("沉默王二".equals(str)) {
list.remove(str);
}
}
for 循環(huán)雖然可以避開 fail-fast 保護(hù)機(jī)制,也就說(shuō) remove 元素后不再拋出異常间坐;但是呢灾挨,這段程序在原則上是有問(wèn)題的邑退。為什么呢?
第一次循環(huán)的時(shí)候劳澄,i 為 0瓜饥,list.size()
為 3,當(dāng)執(zhí)行完 remove 方法后浴骂,i 為 1乓土,list.size()
卻變成了 2,因?yàn)?list 的大小在 remove 后發(fā)生了變化溯警,也就意味著“沉默王三”這個(gè)元素被跳過(guò)了趣苏。能明白嗎?
remove 之前 list.get(1)
為“沉默王三”梯轻;但 remove 之后 list.get(1)
變成了“一個(gè)文章真特么有趣的程序員”食磕,而 list.get(0)
變成了“沉默王三”。
3)使用 Iterator
List<String> list = new ArrayList<>();
list.add("沉默王二");
list.add("沉默王三");
list.add("一個(gè)文章真特么有趣的程序員");
Iterator<String> itr = list.iterator();
while (itr.hasNext()) {
String str = itr.next();
if ("沉默王二".equals(str)) {
itr.remove();
}
}
為什么使用 Iterator 的 remove 方法就可以避開 fail-fast 保護(hù)機(jī)制呢喳挑?看一下 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();
}
}
刪除完會(huì)執(zhí)行 expectedModCount = modCount
,保證了 expectedModCount 與 modCount 的同步伊诵。
簡(jiǎn)單地總結(jié)一下单绑,fail-fast 是一種保護(hù)機(jī)制,可以通過(guò) for-each 循環(huán)刪除集合的元素的方式驗(yàn)證這種保護(hù)機(jī)制曹宴。
那也就是說(shuō)搂橙,for-each 本質(zhì)上是一種語(yǔ)法糖,遍歷集合時(shí)很方面笛坦,但并不適合拿來(lái)操作集合中的元素(增刪)区转。
https://github.com/itwanger/toBeBetterJavaer
這是《Java 程序員進(jìn)階之路》專欄的第 63 篇。Java 程序員進(jìn)階之路版扩,風(fēng)趣幽默废离、通俗易懂,對(duì) Java 初學(xué)者極度友好和舒適??礁芦,內(nèi)容包括但不限于 Java 語(yǔ)法蜻韭、Java 集合框架、Java IO宴偿、Java 并發(fā)編程湘捎、Java 虛擬機(jī)等核心知識(shí)點(diǎn)。
亮白版和暗黑版的 PDF 也準(zhǔn)備好了呢窄刘,一起成為更好的 Java 工程師窥妇,沖!