ホームページ  >  記事  >  Java  >  Java ConcurrentModificationException

Java ConcurrentModificationException

PHPz
PHPzオリジナル
2024-08-30 16:13:30500ブラウズ

Java プログラミング言語はさまざまな例外処理ケースを提供しており、同時変更例外もその 1 つです。同時変更例外は、プログラム内のスレッドが、現在のプロセス中に編集する権限を持たないオブジェクトを変更しようとしたときに発生します。つまり、別のプロセスによって現在使用されているオブジェクトを編集しようとすると、ConcurrentModificationException が表示されます。

無料ソフトウェア開発コースを始めましょう

Web 開発、プログラミング言語、ソフトウェア テスト、その他

非常に単純な例は、スレッドによって処理中のコレクションです。処理中のコレクションは変更できないため、ConcurrentModificationException がスローされます。

構文:

以下は、例外の最も単純な構文です。 ConcurrentModificationException は Java lang RunTimeException の一部であり、それを拡張します。

public class Concurrent Modification Exception
extends Runtime Exception

Java で ConcurrentModificationException はどのように動作しますか?

Java でオブジェクトを作成するときに、必要に応じていくつかの制限と権限を設定することは理解できます。ただし、リストがスレッド内にあるときに、値を変更したり、リストを修正しようとしたりすることがあります。そのとき、オブジェクトは別のスレッドで使用されており、編集または修正できないため、ConcurrentModificationException が表示されます。

この例外は、オブジェクトが同時に変更されていることを必ずしも意味するわけではないことを知っておくことも重要です。単一スレッドの場合、メソッド呼び出しが発生すると、この例外がスローされる可能性があります。これは何らかの形でオブジェクト コントラクトに違反します。

コンストラクター:

ConcurrentModificationException の非常に基本的なコンストラクターは、ConcurrentModificationException () のように単純です。単純なコンストラクターの他に、必要に応じて使用できる次のコントリビューターがあります:

  • ConcurrentModificationException ( String textmessage): 単純なメッセージを含むコンストラクター。
  • ConcurrentModificationException ( String textmessage, Throwable textcause): メッセージと詳細な原因を含むコンストラクター。
  • ConcurrentModificationException ( Throwable textcause): 原因を持つコンストラクター。ここで、原因は null になる可能性があります。これは、原因が不明であることを意味します。

Java ConcurrentModificationException の例

同時変更例外とは何か、そしてそれがどのように機能するかを理解したので、実装に移りましょう。ここで、例を挙げて例外を理解します。たとえば、配列リストがあり、何らかの操作とともにそれを変更しようとすると、例外が発生します。例のコードは次のとおりです:

例 #1

コード:

import java.awt.List;
import java.util.*;
public class ConcurrentModificationException {
public static void main ( String[] args) {
ArrayList<Integer> Numberlist = new ArrayList<Integer> () ;
Numberlist.add ( 1) ;
Numberlist.add ( 2) ;
Numberlist.add ( 3) ;
Numberlist.add ( 4) ;
Numberlist.add ( 5) ;
Iterator<Integer> it = Numberlist.iterator () ;
while ( it.hasNext () ) {
Integer numbervalue = it.next () ;
System.out.println ( "List Value:" + numbervalue) ;
if ( numbervalue .equals ( 3) )
Numberlist.remove ( numbervalue) ;
}
}
}

コードの説明: いくつかのインポート ファイルから始まり、次にクラスの減速と main メソッドです。配列リストを初期化し、数値を加算し続ける関数を追加します。このように、処理中になります。次に追加するたびに、リスト値を出力します。ただし、if ループがあり、3 に等しい数値を探し、3 が見つかるとその数値を削除しようとします。ここで例外が発生し、プログラムが終了します。リストにこれ以上追加されることはありません。

上記のコードをエラーなしで実行すると、コードで例外が発生します。その例外は ConcurrentModificationException.main (ConcurrentModificationException.java:14) にあります。この例外の理由は明らかで、リスト Numberlist を変更しようとしたためです。適切な出力については、以下の添付のスクリーンショットを参照してください:

Java ConcurrentModificationException

ご覧のとおり、プログラムは意図したとおりに実行され、print ステートメントは値 3 に一致するまで正常に実行されました。プログラム フローは値 3 で中断されました。これは、次のような if ループがあったためです。値が 3 の場合は削除します。ただし、イテレータはすでに進行中であるため、3 を削除しようとすると失敗し、例外 ConcurrentModificationException がスローされます。

例 #2

2 番目の例では、同時変更例外を回避するプログラムの実行を試みます。同じコードで、処理中に配列リストを変更しようとすると、ConcurrentModificationException がキャッチされ、プログラムが終了します。 2 番目の例のコードは次のとおりです:

コード:

import java.util.Iterator;
import java.util.ArrayList;
public class ConcurrentModificationException {
public static void main ( String args[])
{
ArrayList<String> arraylist = new ArrayList<String> ( ) ;
arraylist.add ( "One") ;
arraylist.add ( "Two") ;
arraylist.add ( "Three") ;
arraylist.add ( "Four") ;
try {
System.out.println ( "ArrayList: ") ;
Iterator<String> iteratornew = arraylist.iterator () ;
while ( iteratornew.hasNext ( ) ) {
System.out.print ( iteratornew.next ()
+ ", ");
}
System.out.println ( "\n\n Trying to add an element in between iteration:"
+ arraylist.add ( "Five") ) ;
System.out.println ( "\n Updated ArrayList: \n") ;
iteratornew = arraylist.iterator () ;
while ( iteratornew.hasNext ( ) ) {
System.out.print ( iteratornew.next ()
+ ", ");
}
}
catch ( Exception e) {
System.out.println ( e) ;
}
}
}

Code Explanation: Similar to the earlier program, we have the required files and methods. We are simply adding a few elements to the array list, and it is iterating; we add another element, which is Five. We will print the updated list upon the latest additions, which will have our newly added element. We have implemented the try-catch block to catch the exception. If any exception occurs, it will print the exception.

Output:

Java ConcurrentModificationException

As you can see in the output, the first array list is plain, with few elements. Then in the next line, we attempt to add an element while in iteration, the element is “Five”. It is successfully added, and it prints true for the sentence. And in the next line, we print an updated list, which has the Five-element. We have updated the list after the process is ending; if we try to add the element while in the process, it will throw the ConcurrentModificationException, and the program will cease.

How to Avoid ConcurrentModificationException in Java?

Avoiding Concurrent Modification Exception is possible on a different level of threads. To avoid a Concurrent Exception with a single thread environment, you can remove the object from the iterator and modify it, use remove ().

And in the case of a multi-thread environment, you have few choices like converting the list in the process into an array and then working on the array. Then you can also put a synchronized block over a list and lock it. But locking the list is not recommended as it may limit the advantages of multi-threading programming. Using a sublist to modify a list will result in nothing. Out of all the ways to avoid, the most preferred way is to wait until the execution is finished and then edit or modify the list or the object.

Conclusion

When a process is using one resource and another process attempts to edit or amend it, the exception ConcurrentModificationException will be thrown. The simplest method to avoid is to modify the list after iteration. Many methods are listed to avoid the exception but advised to implement them with small programs.

以上がJava ConcurrentModificationExceptionの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。