Skip to content

ConcurrentHashMap vs HashMap

Goeun Moon edited this page May 15, 2025 · 1 revision

비교


  HashMap ConcurrentHashMap
스레드 안전 없음 스레드 안전
동기화 방식 없음 내부적으로 세분화된 락 사용
멀티스레드 환경 충돌, 데이터 손상 가능 안전하게 동시 접근 가능
성능 단일 스레드에서는 빠름 멀티스레드 환경에서 더 적합
null 허용 키와 값 모두 null 허용 키는 null 불가, 값은 가능

ConcurrentHashMap 선택 이유


ConcurrentHashMap은 내부적으로 데이터를 여러 세그먼트로 나누어 부분적으로 lock을 걸기 때문에 전체 맵에 대한 락 없이도 동시 접근이 가능함
부분 락 구조 덕분에 여러 스레드가 병렬로 데이터를 읽고 쓸 수 있어 성능 저하 없이도 스레드 안전성 확보 가능
단일 스레드 환경에서는 HashMap도 충분하지만 멀티스레드 환경에서도 안정성을 보장하기 위해 ConcurrentHashMap을 선택함

변경 사항


기존 코드

private static final Map<Long, UserEntity> store = new HashMap<>();

@Override
public UserEntity save(UserEntity userEntity) {
    Long id = store.isEmpty() ? 0 : (long) store.size();
    store.put(id, userEntity);
    return store.get(id);
}

변경 후

private static final Map<Long, UserEntity> store = new ConcurrentHashMap<>();
// 고유 ID 생성
private final AtomicLong sequence = new AtomicLong(0);

@Override
public UserEntity save(UserEntity userEntity) {
    Long id = sequence.getAndIncrement();
    store.put(id, userEntity);
    return store.get(id);
}

Clone this wiki locally