IT/JAVA
ConcurrentModificationException
최고영회
2019. 5. 21. 13:58
728x90
반응형
SMALL
데이터를 순회하면서 특정 data를 조작(삭제)하고 싶을 때 발생한다.
Iterator<Entry<Long, Date>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<Long, Date> entry = it.next();
if (entry != null && entry.getValue().compareTo(actualExpiredTime) < 0) {
map.remove(entry.getKey());
}
}
Java 공식 문서를 보면 Iterator 의 remove를 이용하는 것이 Collection을 순회하면서 element를 삭제하는 유일하게 안전한 방법이라고 가이드 하고 있다.
그래서 소스코드를 바꿔본다.
Iterator<Entry<Long, Date>> it = map.entrySet().iterator();
while (it.hasNext()) {
Entry<Long, Date> entry = it.next();
if (entry != null && entry.getValue().compareTo(actualExpiredTime) < 0) {
it.remove();
}
}
Tip.
java.util.concurrent에 있는 CopyOnWriteArrayList를 이용해도 처리 가능하다.
Java8 이상에서는 removeIf()라는 메서드를 통해서 쉽게 처리 가능하다.
stream().filter 를 이용해도 된다. (google guava를 이용해도 유사한 filter 가 존재한다.)
728x90
반응형
LIST