代碼:如何在併發線程中操作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