나는 액세스를 동기화해야하는 정적지도가 있습니다. 지도에는 사용자 ID가 입력됩니다. 같은 사용자 ID와 관련된 스레드 만 차단할 수있는 모든 스레드를 차단하지 않도록 동기화를 최적화하려고합니다.정적지도의 항목과 Java 동기화
private static Object s_lock = new Object();
private static Map<String,User> s_users = new HashMap();
...
private someMethod() {
synchronized(s_lock)
{
// keeping the global lock for as little as possible
user=getMapEntry();
}
synchronized(user) <-------- (1)
{
// time consuming operation
// hopefully only blocking threads that relate to same user id.
}
}
...
private User getMapEntry(String userId)
{
if (s_users.containsKey(userId)) {
user = s_users.get(userId);
}
else {
user = new User();
user.id = userId;
s_users.put(userId, user);
}
return user;
}
내 질문은 - (1) 나는 내가 '글로벌'동기화 잠금을 보유하지만, s_users지도가 정적이기 때문에, 난 여전히 유지하고 있음을 의미 효과적으로 정적 항목입니다 아니에요 가정 오전 전역 잠금 (즉, 클래스 개체 동기화)?
ConcurrentHashMap.putIfAbsent()를 사용하면 첫 번째 동기화 블록을 피할 수 있습니다. –