어제 오늘 내일

[Java] Collections.synchronizedSet()으로 스레드 안전한 집합 만들기 본문

IT/Java

[Java] Collections.synchronizedSet()으로 스레드 안전한 집합 만들기

hi.anna 2025. 9. 9. 12:58

멀티스레드 환경에서 여러 스레드가 동시에 같은 Set에 접근하면 문제가 발생할 수 있습니다.
예를 들어, 한 스레드가 데이터를 추가하는 동시에 다른 스레드가 데이터를 삭제한다면 데이터 불일치ConcurrentModificationException이 발생할 수 있습니다.
이런 경우, Collections.synchronizedSet()을 사용하면 간단하게 스레드 안전한 Set을 만들 수 있습니다.
이 메서드는 멀티스레드 환경에서 스레드 안전(Thread-Safe) 한 집합(Set)을 만들 때 사용합니다.

 

1. 기본 사용법

import java.util.*;

public class SyncSetExample1 {
    public static void main(String[] args) {
        Set<String> normalSet = new HashSet<>();
        Set<String> syncSet = Collections.synchronizedSet(normalSet);

        syncSet.add("apple");
        syncSet.add("banana");
        syncSet.add("cherry");

        System.out.println(syncSet);
    }
}

실행 결과

[banana, cherry, apple]

👉 HashSet을 감싼 스레드 안전한 Set이 만들어졌습니다.

 

2. 동기화된 반복문 사용하기

synchronizedSetadd, remove, contains 같은 메서드는 자동으로 동기화되지만,
반복(iteration) 은 수동으로 동기화해야 안전합니다.

import java.util.*;

public class SyncSetExample2 {
    public static void main(String[] args) {
        Set<Integer> set = Collections.synchronizedSet(new HashSet<>());
        set.add(1);
        set.add(2);
        set.add(3);

        // 안전한 반복
        synchronized (set) {
            for (int num : set) {
                System.out.println(num);
            }
        }
    }
}

👉 반복 시에는 반드시 synchronized(set) 블록 안에서 순회해야 합니다.

 

3. 활용 예시

  • 멀티스레드 환경에서 중복 없는 데이터 관리
  • 작업 ID 관리: 여러 스레드가 동시에 고유 ID를 기록할 때
  • 중복 방지 로그 수집기: 중복되지 않는 이벤트만 모아야 할 때

 

4. 주의할 점

  • Collections.synchronizedSet()기존 Set을 감싼 래퍼(wrapper) 입니다.
  • 메서드 호출은 자동 동기화되지만, 반복문은 수동 동기화 필요합니다.
  • 고성능 멀티스레드 환경에서는 ConcurrentSkipListSet 같은 대안이 더 적합할 수 있습니다.

 

5. 정리

  • Collections.synchronizedSet(Set<T> s)
    👉 주어진 Set을 감싼 스레드 안전한 Set 반환
  • 메서드 호출은 자동 동기화, 반복문은 synchronized 블록 필요
  • 멀티스레드 환경에서 안전하게 Set을 사용할 수 있음

👉 여러 스레드에서 안전하게 Set을 쓰고 싶다면 Collections.synchronizedSet()으로 감싸자!

 

 

반응형
Comments