代码:如何在并发线程中操作values()和put()时避免HashMap“ConcurrentModificationException”?
我有一个HashMap
private Map<K, V> map = new HashMap<>();
一种方法将把ķ-V对进入它通过调用put(K,V)
。
另一种方法想从它的值提取一组随机元素:
int size = map.size(); // size > 0
V[] value_array = map.values().toArray(new V[size]);
Random rand = new Random();
int start = rand.nextInt(size); int end = rand.nextInt(size);
// return value_array[start .. end - 1]
的两种方法称为在两个不同的并发线程。
错误:
我有一个ConcurrentModificationException
错误:
at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
at java.util.HashMap$ValueIterator.next(Unknown Source)
at java.util.AbstractCollection.toArray(Unknown Source)
看来,在一个线程中toArray()
方法实际上是遍历HashMap和其他线程put()
修改发生。
Question: How to avoid "ConcurrentModificationException" while using HashMap.values().toArray() and HashMap.put() in concurrent threads?
Directly avoiding usingvalues().toArray()
in the second method is also OK.
执行访问了'map'在同步块中的代码:'同步(图){...}'' – Titus 2014-10-29 02:38:40
同步(图){...}'应该工作(如果你处处应用它)。 Collections.synchronizedMap不起作用。请参阅http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedMap%28java.util.Map%29 – Thilo 2014-10-29 03:15:06