새소식

반응형
Language/Java

[Java] ConcurrentModificationException 예외 처리 및 원인

  • -
반응형

2023-04-28


사진: Unsplash 의 Willian Justen de Vasconcellos


1. 원인

 

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

이 예외는 객체의 동시 수정이 허용되지 않을 때 객체의 동시 수정을 탐지한 방법에 의해 발생할 수 있습니다.

 

For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. 

예를 들어, 다른 스레드가 컬렉션을 반복하는 동안 한 스레드가 컬렉션을 수정하는 것은 일반적으로 허용되지 않습니다. 일반적으로 이러한 상황에서는 반복 결과가 정의되지 않습니다.

 

Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future.

일부 Iterator 구현(JRE에서 제공하는 모든 범용 수집 구현 포함)은 이 동작이 탐지될 경우 이 예외를 발생시킬 수 있습니다. 이를 반복하는 반복자는 미래의 결정되지 않은 시간에 임의적이고 결정론적이지 않은 행동을 감수하기보다는 빠르고 깨끗하게 실패하기 때문에 오류 발생 속도가 빠른 반복자로 알려져 있습니다.

 

Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. 

이 예외가 항상 개체가 다른 스레드에 의해 동시에 수정되었음을 나타내는 것은 아닙니다. 단일 스레드가 개체의 계약을 위반하는 메서드 호출 시퀀스를 실행하는 경우 개체가 이 예외를 발생시킬 수 있습니다.

 

For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception

예를 들어, 스레드가 Fail-Fast Iterator를 사용하여 컬렉션을 반복하는 동안 컬렉션을 직접 수정하는 경우, Iterator는 이 예외를 던집니다

 

요약하자면 The enhanced for statement(향산된 for 문)의 경우 Iterator을 이용해 반복하게 된다. iterator는 컬력션 객체이며, 자바는 이러한 컬렉션 객체가 반복되는 동안 해당 객체를 다른 스레드 객체가 수정하는 것을 금하기 때문에 오류가 발생하게 된다는 것이다.


2. test 코드

	@Test
	public void test1(){
		List<String> list1 = new ArrayList<String>();
		list1.add("a");
		list1.add("b");
		list1.add("c");

		try{
			for(String str : list1){
				if(str.equals("a")) list1.remove("a");
			} //java.util.ConcurrentModificationException
		}catch (ConcurrentModificationException e){
			System.out.println("=====java.util.ConcurrentModificationException=====");
		}
		toStringList(list1);

		for(int i = 0; i < list1.size(); i++){
			if(list1.get(i).equals("a")) list1.remove("a");
		}
		toStringList(list1);
	}
    
    
    	public void toStringList(List<String> list1){
		System.out.println("================================================================");
		for (String str : list1) System.out.println("str ->" + str);
		System.out.println("================================================================");
		System.out.println();
	}

메인 이미지 출처 : 사진: UnsplashWillian Justen de Vasconcellos  

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.