目次
Java で ConcurrentModificationException はどのように動作しますか?
Java ConcurrentModificationException の例
例 #2
How to Avoid ConcurrentModificationException in Java?
Conclusion
ホームページ Java &#&チュートリアル Java ConcurrentModificationException

Java ConcurrentModificationException

Aug 30, 2024 pm 04:13 PM
java

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 までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

PHP対Python:違いを理解します PHP対Python:違いを理解します Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHPは、シンプルな構文と高い実行効率を備えたWeb開発に適しています。 2。Pythonは、簡潔な構文とリッチライブラリを備えたデータサイエンスと機械学習に適しています。

PHP:Web開発の重要な言語 PHP:Web開発の重要な言語 Apr 13, 2025 am 12:08 AM

PHPは、サーバー側で広く使用されているスクリプト言語で、特にWeb開発に適しています。 1.PHPは、HTMLを埋め込み、HTTP要求と応答を処理し、さまざまなデータベースをサポートできます。 2.PHPは、ダイナミックWebコンテンツ、プロセスフォームデータ、アクセスデータベースなどを生成するために使用され、強力なコミュニティサポートとオープンソースリソースを備えています。 3。PHPは解釈された言語であり、実行プロセスには語彙分析、文法分析、編集、実行が含まれます。 4.PHPは、ユーザー登録システムなどの高度なアプリケーションについてMySQLと組み合わせることができます。 5。PHPをデバッグするときは、error_reporting()やvar_dump()などの関数を使用できます。 6. PHPコードを最適化して、キャッシュメカニズムを使用し、データベースクエリを最適化し、組み込み関数を使用します。 7

Java 8 Stream Foreachから休憩または戻ってきますか? Java 8 Stream Foreachから休憩または戻ってきますか? Feb 07, 2025 pm 12:09 PM

Java 8は、Stream APIを導入し、データ収集を処理する強力で表現力のある方法を提供します。ただし、ストリームを使用する際の一般的な質問は次のとおりです。 従来のループにより、早期の中断やリターンが可能になりますが、StreamのForeachメソッドはこの方法を直接サポートしていません。この記事では、理由を説明し、ストリーム処理システムに早期終了を実装するための代替方法を調査します。 さらに読み取り:JavaストリームAPIの改善 ストリームを理解してください Foreachメソッドは、ストリーム内の各要素で1つの操作を実行する端末操作です。その設計意図はです

PHP対その他の言語:比較 PHP対その他の言語:比較 Apr 13, 2025 am 12:19 AM

PHPは、特に迅速な開発や動的なコンテンツの処理に適していますが、データサイエンスとエンタープライズレベルのアプリケーションには良くありません。 Pythonと比較して、PHPはWeb開発においてより多くの利点がありますが、データサイエンスの分野ではPythonほど良くありません。 Javaと比較して、PHPはエンタープライズレベルのアプリケーションでより悪化しますが、Web開発により柔軟性があります。 JavaScriptと比較して、PHPはバックエンド開発により簡潔ですが、フロントエンド開発のJavaScriptほど良くありません。

PHP対Python:コア機能と機能 PHP対Python:コア機能と機能 Apr 13, 2025 am 12:16 AM

PHPとPythonにはそれぞれ独自の利点があり、さまざまなシナリオに適しています。 1.PHPはWeb開発に適しており、組み込みのWebサーバーとRich Functionライブラリを提供します。 2。Pythonは、簡潔な構文と強力な標準ライブラリを備えたデータサイエンスと機械学習に適しています。選択するときは、プロジェクトの要件に基づいて決定する必要があります。

PHPの影響:Web開発など PHPの影響:Web開発など Apr 18, 2025 am 12:10 AM

phphassiblasifly-impactedwebdevevermentandsbeyondit.1)itpowersmajorplatformslikewordpratsandexcelsindatabase interactions.2)php'sadaptableability allowsitale forlargeapplicationsusingframeworkslikelavel.3)

PHP:多くのウェブサイトの基礎 PHP:多くのウェブサイトの基礎 Apr 13, 2025 am 12:07 AM

PHPが多くのWebサイトよりも優先テクノロジースタックである理由には、その使いやすさ、強力なコミュニティサポート、広範な使用が含まれます。 1)初心者に適した学習と使用が簡単です。 2)巨大な開発者コミュニティと豊富なリソースを持っています。 3)WordPress、Drupal、その他のプラットフォームで広く使用されています。 4)Webサーバーとしっかりと統合して、開発の展開を簡素化します。

PHP対Python:ユースケースとアプリケーション PHP対Python:ユースケースとアプリケーション Apr 17, 2025 am 12:23 AM

PHPはWeb開発およびコンテンツ管理システムに適しており、Pythonはデータサイエンス、機械学習、自動化スクリプトに適しています。 1.PHPは、高速でスケーラブルなWebサイトとアプリケーションの構築においてうまく機能し、WordPressなどのCMSで一般的に使用されます。 2。Pythonは、NumpyやTensorflowなどの豊富なライブラリを使用して、データサイエンスと機械学習の分野で驚くほどパフォーマンスを発揮しています。

See all articles