一个系统中有两个线程。一个是读者线程,另一个是作者线程。
使用以下代码同步 map 。
Map<String,ArrayList<String>> m = Collections.synchronizedMap(new HashMap<String,ArrayList<String>())
读取线程获取映射值的迭代器,同时写入线程修改映射。
所以,我的问题是 Iterator 会抛出 ConcurrentModificationException
吗?
最佳答案
也许吧。这样做不安全。 documentation说
It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views
Collections.synchronized...
使单个方法调用原子化,因此它们不需要进一步同步。但是迭代不仅仅是一个单一的方法调用,所以它需要额外的同步。下面是一个例子
Map<String, String> shared = Collections.synchronizedMap(new HashMap<>());
new Thread(() -> {
while (true) {
synchronized (shared) {
for (String key : shared.keySet()) {
System.out.println(key);
}
}
try {
Thread.sleep(1000);
} catch (Exception e) {
break;
}
}
}).start();
new Thread(() -> {
while (true) {
try {
// this is atomic
shared.put(UUID.randomUUID().toString(), "Yo!");
Thread.sleep(1000);
} catch (Exception e) {
break;
}
}
}).start();
}
关于java - Collections.synchronized 映射是否使 Iterator 线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33190500/