【发布时间】:2014-05-27 07:41:46
【问题描述】:
在有关 synchronizedMap 的教程中,我遇到了以下代码(教程中的 cmets):
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());
}
我在源代码中看到迭代器方法没有被同步部分包装。没关系。
我害怕得到意想不到的东西
Set s = m.keySet();
// Could happen something unexpected here ?
synchronized(m) {
请说明为什么这段代码是安全的?
synchronized(m) { // Synchronizing on m, not s!
Set s = m.keySet(); // Needn't be in synchronized block
Iterator i = s.iterator(); // Must be in synchronized block
while (i.hasNext())
foo(i.next());
}
这种同步是否过度?
【问题讨论】:
标签: java collections iterator synchronization