>  기사  >  Java  >  Java ConcurrentModificationException

Java ConcurrentModificationException

PHPz
PHPz원래의
2024-08-30 16:13:30500검색

Java 프로그래밍 언어는 다양한 예외 처리 사례를 제공하며 동시 수정 예외도 그 중 하나입니다. 동시 수정 예외는 프로그램의 스레드가 현재 프로세스에서 편집할 수 있는 권한이 없는 개체를 수정하려고 할 때 발생합니다. 간단히 말해, 현재 다른 프로세스에서 사용 중인 개체를 편집하려고 하면 ConcurrentModificationException이 나타납니다.

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

아주 간단한 예로 스레드로 처리 중인 컬렉션을 들 수 있습니다. 프로세스 중인 컬렉션은 수정이 허용되지 않으므로 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) ;
}
}
}

코드 설명: 몇 가지 가져오기 파일로 시작한 다음 클래스 감속 및 기본 메서드를 사용합니다. 배열 목록을 초기화하고 숫자를 계속 추가하는 함수를 추가합니다. 이렇게 하면 처리가 진행됩니다. 다음에 추가할 때마다 목록 값이 인쇄됩니다. 그러나 if 루프는 3과 같은 숫자를 찾고 3이 발견되면 숫자를 제거하려고 시도하며 여기서 예외가 발생하고 프로그램이 종료됩니다. 목록에 더 이상 추가되지 않습니다.

위 코드를 오류 없이 실행하면 코드에서 예외가 발생합니다. 해당 예외는 ConcurrentModificationException.main( ConcurrentModificationException.java:14)에 있습니다. 이 예외가 발생하는 이유는 Numberlist라는 목록을 수정하려고 시도했기 때문입니다. 올바른 출력을 위해 아래 첨부된 스크린샷을 참조하세요.

Java ConcurrentModificationException

보시다시피 프로그램은 의도한 대로 실행되었으며 print 문은 값 3에 도달할 때까지 성공적으로 실행되었습니다. if 루프가 있었기 때문에 프로그램 흐름이 값 3에서 중단되었습니다. 3과 같은 값을 삭제합니다. 그러나 반복자는 이미 진행 중이므로 3을 삭제하려는 시도는 실패하며 이로 인해 ConcurrentModificationException 예외가 발생합니다.

예시 #2

두 번째 예에서는 동시 수정 예외를 성공적으로 회피하는 프로그램을 실행해 보겠습니다. 동일한 코드에서 처리 중에 배열 목록을 수정하려고 하면 ConcurrentModificationException이 발생하고 프로그램이 종료됩니다. 두 번째 예시의 코드는 다음과 같습니다.

코드:

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.