【发布时间】:2012-12-06 04:16:32
【问题描述】:
我对创建同步静态对象有足够的了解。 但是对于 Java 中的地图(集合),
我在 Java 中单独找到了默认实现(一个用于同步列表,一个用于单例映射)。
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Collections.html#synchronizedMap(java.util.Map) http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Collections.html#singletonMap(K,V)
我正在考虑通过以下实现来获得预期的结果
Map<K,V> initMap = new HashMap<K,V>();
Map<K,V> syncSingMap = Collections.synchronizedMap(Collection.singletonMap(initMap));
我说得对吗?因为 oracle 的文档对此显示了一些警告
It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views:
Map m = Collections.synchronizedMap(new HashMap());
...
Set s = m.keySet(); // Needn't be in synchronized block
...
synchronized(m) { // Synchronizing on m, not s!
Iterator i = s.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}
Failure to follow this advice may result in non-deterministic behavior
如何在此之上使用 ConcurrentMap。
要求:静态同步单例映射,将被大量线程用于某些处理操作
更新
看了几篇文章,发现ConcurrentMap在多线程环境下比HashMap好很多 http://java.dzone.com/articles/java-7-hashmap-vs
【问题讨论】:
-
singletonMap 用于单个元素,而不是地图的单个实例。
-
您可能最好使用 ConcurrentMap(我假设您将修改地图?)
-
是的。一旦线程完成它的工作,我将通过从地图中获取一些东西来修改地图
标签: java multithreading synchronization hashmap