'ConcurrentModificationException' 트러블 슈팅

jy.YOON·2022년 9월 15일

트러블슈팅

목록 보기
2/4

자료구조에서의 ConcurrentModificationException 문제

문제의 코드

        Map<Integer, InOutRecords> check = new LinkedHashMap<>();
        ...
        ...
           
        Iterator<Integer> keys = check.keySet().iterator();
            while (keys.hasNext()) {
                int key = keys.next();
                //int totalFee = calculate(check.get(key).getTime(), "23:59", fees);
                int min = totalTimeByMin(check.get(key).getTime(), lastTime);
                accumulate.put(key, accumulate.get(key) + min);
                check.remove(key);
            }
        ...
        ...

문제 발생지점

HashMap 구조에서 while을 통해 키값을 순회하면서 동시에

check.remove(key) 를 사용하여 키값을 삭제 하는것이 문제였다.

변경될 코드

Map<Integer, InOutRecords> check = new LinkedHashMap<>();

LinkedHashMap 에서 ConcurrentHashMap으로 변경하여 동기화를 보장할수 있도록 하자

Map<Integer, InOutRecords> check = new ConcurrentHashMap<>();

profile
5 Seconds rule

0개의 댓글