<aside> 💡
wait과 notify보다 고수준 동시성 유틸리티 사용할 것.
</aside>
아이템 80에서 언급함.
List, Queue, Map과 같은 표준 컬렉션 인터페이스에 동시성을 추가해 구현한 고성능 컬렉션. 높은 동시성에 도달하기 위해 동기화를 각자의 내부에서 수행한다.
→ 동시성 컬렉션에서 동시성 무력화 불가능, 외부에서 락을 추가로 사용하면 오히려 속도가 느려짐
→ 여러 메서드 원자적을 묶어서 호출하는 일 불가능
상태 의존적 수정 메서드 등장
String.intern 동작 흉내내 구현한 메서드
public class Intern {
// ConcurrentMap으로 구현한 동시성 정규화 맵 - 최적 아님
private static final ConcurrentMap<String, String> map =
new ConcurrentHashMap<>();
public static String intern(String s) {
String previousValue = map.putIfAbsent(s, s);
return previousValue == null ? s : previousValue;
}
// ConcurrentMap으로 구현한 동시성 정규화 맵 - 더 빠름
public static String intern(String s) {
//get을 먼저 호출해 필요할 때만 putIfAbsent 호출
String result = map.get(s);
if (result == null) {
result = map.putIfAbsent(s, s);
if (result == null)
result = s;
}
return result;
}
}
ConcurrentHashMap은 동시성 뛰어나고 속도도 빠름. (String.intern에는 오래 실행되는 프로그램에서 메모리 누수 방지하는 기술도 들어가 있긴 함)