title: How to avoid HashMap "ConcurrentModificationException" while manipulating `values()` and `put()` in concurrent threads?
body: <p><em>Code:</em></p>
  
  <p>I have a HashMap</p>
  
  <pre><code>private Map&lt;K, V&gt; map = new HashMap&lt;&gt;();
  </code></pre>
  
  <p>One method will put K-V pair into it by calling <code>put(K,V)</code>. </p>
  
  <p>The other method wants to extract a set of random elements from its values:</p>
  
  <pre><code>int size = map.size();    // size &gt; 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]
  </code></pre>
  
  <p>The two methods are called in two different <strong>concurrent threads</strong>.</p>
  
  <hr>
  
  <p><em>Error:</em></p>
  
  <p>I got a <code>ConcurrentModificationException</code> error:</p>
  
  <pre><code>at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
  at java.util.HashMap$ValueIterator.next(Unknown Source)
  at java.util.AbstractCollection.toArray(Unknown Source)
  </code></pre>
  
  <p>It seems that the <code>toArray()</code> method in one thread is actually iterating over the HashMap and a <code>put()</code> modification in other thread occurs.</p>
  
  <blockquote>
    <p><em>Question:</em> How to avoid "ConcurrentModificationException" while using HashMap.values().toArray() and HashMap.put() in concurrent threads?<br>
    Directly avoiding using <code>values().toArray()</code> in the second method is also OK.</p>
  </blockquote>