the code:
I have a hashmap
private Map<K, V> map = new HashMap<>();
One method will put a pair of KV in it, calling put(K,V) .
Another method wants to extract a set of random elements from their values:
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]
Two methods are called in two different parallel threads .
Error:
I got a ConcurrentModificationException error:
at java.util.HashMap$HashIterator.nextEntry(Unknown Source) at java.util.HashMap$ValueIterator.next(Unknown Source) at java.util.AbstractCollection.toArray(Unknown Source)
It seems that the toArray() method in one thread actually iterates over the HashMap, and put() is being modified in another thread.
Question: How to avoid "ConcurrentModificationException" when using HashMap.values โโ(). toArray () and HashMap.put () in parallel threads?
Directly avoiding the use of values().toArray() in the second method is also good.
source share