java

java Map ConcurrentModificationException 회피

kimbs0301 2024. 7. 4. 14:35
더보기

java.util.HashMap
java.util.LinkedHashMap
java.util.concurrent.locks.ReentrantLock

 

ConcurrentModificationException이 발생하는 경우는 2가지가 있다고 합니다.
1. 서로 다른 Thread가 동시에 같은 HashMap에 연산을 수행함
2. for문 안에서 HashMap의 entry를 제거함

 

ReentrantLock mutex = new ReentrantLock(true);

    @Test
    void test1() throws Exception {
        map.put("a", Map.of(1L, 1));
        map.put("b", Map.of(2L, 2));
        map.put("c", Map.of(3L, 3));

        mutex.lock();
        try {
            for (String clientIp : map.keySet()) {
                Map<Long, Integer> innerMap = map.get(clientIp);
                // ...
                map.remove(clientIp);
            }
        } finally {
            mutex.unlock();
        }
    }

 

ConcurrentModificationException이 발생

 

ReentrantLock mutex = new ReentrantLock(true);

    @Test
    void test1() throws Exception {
        map.put("a", Map.of(1L, 1));
        map.put("b", Map.of(2L, 2));
        map.put("c", Map.of(3L, 3));

        mutex.lock();
        try {
            Set<String> keySet = new LinkedHashSet<>(map.keySet());
            for (String clientIp : keySet) {
                Map<Long, Integer> innerMap = map.get(clientIp);
                // ...
                if (innerMap != null)
                    map.remove(clientIp);
            }
        } finally {
            mutex.unlock();
        }
    }

 

 

더보기

Set keySet = new LinkedHashSet<>(map.keySet());
Set keySet = new HashSet<>(map.keySet());

키 복사를 통한 ConcurrentModificationException 예외 회피

'java' 카테고리의 다른 글

java drawing random  (1) 2024.07.05
java windows 백그라운드 실행 및 종료  (0) 2024.07.04
java Mutable value  (0) 2024.07.04
java 8byte guid 생성  (0) 2024.07.04
java Virtual Thread Producer Consumer 패턴  (0) 2024.07.04