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) ; } } }</integer></integer></integer>
코드 설명: 몇 가지 가져오기 파일로 시작한 다음 클래스 감속 및 기본 메서드를 사용합니다. 배열 목록을 초기화하고 숫자를 계속 추가하는 함수를 추가합니다. 이렇게 하면 처리가 진행됩니다. 다음에 추가할 때마다 목록 값이 인쇄됩니다. 그러나 if 루프는 3과 같은 숫자를 찾고 3이 발견되면 숫자를 제거하려고 시도하며 여기서 예외가 발생하고 프로그램이 종료됩니다. 목록에 더 이상 추가되지 않습니다.
위 코드를 오류 없이 실행하면 코드에서 예외가 발생합니다. 해당 예외는 ConcurrentModificationException.main( ConcurrentModificationException.java:14)에 있습니다. 이 예외가 발생하는 이유는 Numberlist라는 목록을 수정하려고 시도했기 때문입니다. 올바른 출력을 위해 아래 첨부된 스크린샷을 참조하세요.
보시다시피 프로그램은 의도한 대로 실행되었으며 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) ; } } }</string></string></string>
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:
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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

이 기사에서는 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 및 Gradle을 사용하여 접근 방식과 최적화 전략을 비교합니다.

이 기사에서는 Maven 및 Gradle과 같은 도구를 사용하여 적절한 버전 및 종속성 관리로 사용자 정의 Java 라이브러리 (JAR Files)를 작성하고 사용하는 것에 대해 설명합니다.

이 기사는 카페인 및 구아바 캐시를 사용하여 자바에서 다단계 캐싱을 구현하여 응용 프로그램 성능을 향상시키는 것에 대해 설명합니다. 구성 및 퇴거 정책 관리 Best Pra와 함께 설정, 통합 및 성능 이점을 다룹니다.

이 기사는 캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA를 사용하는 것에 대해 설명합니다. 잠재적 인 함정을 강조하면서 성능을 최적화하기위한 설정, 엔티티 매핑 및 모범 사례를 다룹니다. [159 문자]

Java의 클래스 로딩에는 부트 스트랩, 확장 및 응용 프로그램 클래스 로더가있는 계층 적 시스템을 사용하여 클래스로드, 링크 및 초기화 클래스가 포함됩니다. 학부모 위임 모델은 핵심 클래스가 먼저로드되어 사용자 정의 클래스 LOA에 영향을 미치도록합니다.

이 기사에서는 분산 응용 프로그램을 구축하기위한 Java의 원격 메소드 호출 (RMI)에 대해 설명합니다. 인터페이스 정의, 구현, 레지스트리 설정 및 클라이언트 측 호출을 자세히 설명하여 네트워크 문제 및 보안과 같은 문제를 해결합니다.

이 기사는 네트워크 통신을위한 Java의 소켓 API, 클라이언트 서버 설정, 데이터 처리 및 리소스 관리, 오류 처리 및 보안과 같은 중요한 고려 사항에 대해 자세히 설명합니다. 또한 성능 최적화 기술, i

이 기사에서는 맞춤형 Java 네트워킹 프로토콜을 작성합니다. 프로토콜 정의 (데이터 구조, 프레임, 오류 처리, 버전화), 구현 (소켓 사용), 데이터 직렬화 및 모범 사례 (효율성, 보안, Mainta를 포함합니다.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

mPDF
mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

SublimeText3 Linux 새 버전
SublimeText3 Linux 최신 버전

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

뜨거운 주제



