【发布时间】:2011-12-04 16:39:28
【问题描述】:
我有一个静态地图,我需要同步访问。地图由用户 ID 键入。我想优化同步,这样我就不会阻塞所有线程,我只能阻塞与同一用户 ID 相关的线程。
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() 避免第一个同步块。
标签: java static synchronization