Java

[Java] ConcurrentHashMap

snail voyager 2023. 9. 13. 23:46
728x90
반응형

ConcurrentHashMap

  • 동시성 친화적
  • 내부 자료구조의 특정 부분만 잠궈 동시 추가, 갱신 작업 허용
  • 동기화된 HashMap 보다 읽기 쓰기 연산 성능이 월등
  • forEach : 각(키, 값) 쌍에 주어진 액션을 수행 forEach, forEachKey, forEachValue, forEachEntry
  • reduce : 모든(키, 값) 쌍을 제공된 reduce 함수를 이용해 결과로 합침 reduce, reduceKeys, reduceValues, reduceEntries
  • search : null이 아닌 값을 반환할 때까지 각(키, 값) 쌍에 함수를 적용 search, searchKeys, searchValues, searchEntries
  • 계산이 진행되는 동안 바뀔 수 있는 객체, 값, 순서 등에 의존하지 않아야함
  • 병렬성 기준값 threshold를 지정
  • Map의 크기가 기준값보다 작으면 순차적으로 연산
  • 기본값 전용 reduce 연산 reduceValuesToInt, reduceKeysToLong
// ConcurrentHashMap 생성
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

// 맵에 데이터 추가
map.put("apple", 3);
map.put("banana", 2);
map.put("cherry", 5);
map.put("date", 1);

// 값을 모두 합산하는 병렬 리듀스 작업 수행
long sum = map.reduceValues(2, (key, value) -> value, Integer::sum);

// 결과 출력
System.out.println("Sum of values: " + sum);	//11

mappingCount()

  • 현재 맵의 엔트리(키-값 쌍) 수를 반환
  • 스캔 연산은 병렬로 실행되며, 맵의 엔트리 수를 정확하게 반환
  • 엔트리 수가 int의 범위를 넘어서는 상황을 대처
  • size() 메서드는 정확한 엔트리 수를 반환하지 않을 수 있으며,
  • 근사치를 빠르게 계산하기 위해 내부적으로 사용하는 방식에 따라 결과가 다를 수 있음
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

// 맵에 데이터 추가
map.put("apple", 3);
map.put("banana", 2);
map.put("cherry", 5);
map.put("date", 1);

// 맵의 엔트리 수 조회
long count = map.mappingCount();

// 결과 출력
System.out.println("엔트리 수: " + count);	//4

keySet()

  • 맵의 키(key) 집합을 반환
  • Set 인터페이스를 구현한 컬렉션으로, 중복되지 않는 고유한 키들의 집합
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

// 맵에 데이터 추가
map.put("apple", 3);
map.put("banana", 2);
map.put("cherry", 5);
map.put("date", 1);

// 키 집합 얻기
Set<String> keySet = map.keySet();

// 키 집합 순회하며 출력
for (String key : keySet) {
    System.out.println("Key: " + key + ", Value: " + map.get(key));
}

newKeySet()

  • 맵과 동기화된 ConcurrentHashMap.KeySetView 객체를 생성
  • 이 객체는 맵의 키(key) 집합을 나타내며 ConcurrentHashMap과 연결되어 있으므로 맵의 변경 사항을 실시간으로 반영
  • 이 Set 객체를 통해 맵의 키(key)를 변경하면 해당 변경 사항이 맵에도 반영
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

// 키 집합 얻기
Set<String> keySet = map.newKeySet();

// 맵에 데이터 추가
map.put("apple", 3);
map.put("banana", 2);
map.put("cherry", 5);

// 키 집합을 통해 키 추가
keySet.add("date");

// 결과 출력
System.out.println("Map: " + map); // 출력: {apple=3, banana=2, cherry=5, date=null}
728x90
반응형