【发布时间】:2015-09-01 07:57:17
【问题描述】:
我有一个类容器,其中包含一个将被多个线程使用的集合:
public class Container{
private Map<String, String> map;
//ctor, other methods reading the map
public void doSomeWithMap(String key, String value){
//do some threads safe action
map.put(key, value);
//do something else, also thread safe
}
}
有什么更好的办法,声明方法synchronized:
public synchronized void doSomeWithMap(String key, String value)
还是使用标准的线程安全装饰器?
Collections.synchronizedMap(map);
【问题讨论】:
-
如果您不需要自己处理并发,请在此处查看此地图docs.oracle.com/javase/7/docs/api/java/util/concurrent/…
-
两者都不 - 使用ConcurrentHashMap :)
-
@TheLostMind 不清楚,为什么同步方法是错误的?
-
@St.Antario - 这不好,因为您将锁定整个地图实例,而在
ConcurrentHashMap中,您将查看更有效的特定段。
标签: java multithreading collections