我正在使用以下构造来创建线程安全的 Map
。
Collections.synchronizedMap(new LinkedHashMap());
尽管我遇到了 ConcurrentModificationException
错误。
最佳答案
如果没有代码,很难猜测真正的问题是什么,但我的猜测是,您没有使用返回的集合来执行操作。根据 javadoc
In order to guarantee serial access, it is critical that all access to the backing collection is accomplished through the returned collection. It is imperative that the user manually synchronize on the returned collection when iterating over it:
Collection c = Collections.synchronizedCollection(myCollection);
...
synchronized(c) {
Iterator i = c.iterator(); // Must be in the synchronized block
while (i.hasNext())
foo(i.next());
}
不遵循此建议可能会导致不确定的行为。
关于java - Collections.synchronizedMap(new LinkedHashMap());没有使 Map 线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13151166/