日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java Essentials: Preventing ConcurrentModificationException

發布時間:2024/5/15 java 67 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java Essentials: Preventing ConcurrentModificationException 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一.參考
1.Java Essentials: Preventing ConcurrentModificationException
https://www.codebyamir.com/blog/java-essentials-preventing-concurrentmodificationexception

二.
Overview
The JVM will throw a ConcurrentModificationException at runtime whenever we try to modify a collection while iterating over it.

In this article, we’ll explain why this happens and some solutions to prevent this.

Example
Suppose we populate a list with names and then later want to remove some names from the list.

Code
We may write something like this:

List names = new ArrayList<>();

names.add(“Amir”);
names.add(“Beth”);
names.add(“Arnie”);
names.add(“Lucy”);

for (String name : names) {
if (name.startsWith(“A”)) {
names.remove(name);
}
}

System.out.println(names);
Output
This code will compile successfully but throw an exception at runtime on line 10:

Exception in thread “main” java.util.ConcurrentModificationException
at java.util.ArrayList I t r . c h e c k F o r C o m o d i f i c a t i o n ( U n k n o w n S o u r c e ) a t j a v a . u t i l . A r r a y L i s t Itr.checkForComodification(Unknown Source) at java.util.ArrayList Itr.checkForComodification(UnknownSource)atjava.util.ArrayListItr.next(Unknown Source)
at com.codebyamir.demo.Main.main(Main.java:10)
Notice that this may only happen intermittently because we are calling remove() inside a conditional statement. So the exception will be thrown whenever we have a String that starts with “A” in our list.

Solutions
There are a number of ways to prevent ConcurrentModificationException, and we’ll explore these below.

Use an Iterator
We can change how we iterate by replacing the enhanced for-loop with a while loop that uses an Iterator object. The Iterator allows us to safely remove the matching element because we are not calling remove() directly on the list object.

Code
List names = new ArrayList<>();

names.add(“Amir”);
names.add(“Beth”);
names.add(“Arnie”);
names.add(“Lucy”);

Iterator iter = names.iterator();

while (iter.hasNext()) {
String name = iter.next();

if (name.startsWith(“A”)) {
iter.remove();
}
}

System.out.println(names);
Output
[Beth, Lucy]

Populate a separate list to keep track of the items to be removed
This approach avoids having to introduce an Iterator object, but it requires another list to keep track of the names we want to remove.

Code
List names = new ArrayList<>();

names.add(“Amir”);
names.add(“Beth”);
names.add(“Arnie”);
names.add(“Lucy”);

List removeNames = new ArrayList<>();

for (String name : names) {
if (name.startsWith(“A”)) {
removeNames.add(name);
}
}

names.removeAll(removeNames);
Output
[Beth, Lucy]

Use Java 8’s removeIf() method
Java 8 added the removeIf() method to the java.util.Collection class.

JDK Code
Let’s take a look at the JDK code for this method. Notice how it uses an Iterator under the hood.

public boolean removeIf(Predicate paramPredicate) {
Objects.requireNonNull(paramPredicate);
boolean bool = false;
Iterator localIterator = iterator();
while (localIterator.hasNext()) {
if (paramPredicate.test(localIterator.next())) {
localIterator.remove();
bool = true;
}
}
return bool;
}
Code
This method makes our code more concise since we can use a Lambda expression.

List names = new ArrayList<>();

names.add(“Amir”);
names.add(“Beth”);
names.add(“Arnie”);
names.add(“Lucy”);

names.removeIf(name -> (name.startsWith(“A”)));
Output
[Beth, Lucy]

Note that ArrayList has an optimized implementation of `removeIf`` (http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/util/ArrayList.java/#1393) which makes it the fastest solution.

總結

以上是生活随笔為你收集整理的Java Essentials: Preventing ConcurrentModificationException的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。