title: Safely iterate an ConcurrentHashMap that is accessed by multiple thread
body: <p>I have a ConcurrentHashMap object which is shared by multiple threads to access:</p>
  
  <pre><code>Map&lt;String, MyConnection&gt; myMap = new ConcurrentHashMap&lt;String, MyConnection&gt;();
  </code></pre>
  
  <p>The class MyConnection contains some connection to the datasource.</p>
  
  <p>At a later stage, I need to iterate the ConcurrentHashMap, call MyConnection.close() method and remove it from the Map. Something like this:</p>
  
  <pre><code>for(String key : myMap.ketSet()) {
      MyConnection connection = myMap.get(key);
      connection.close();
      myMap.remove(key);
  }
  </code></pre>
  
  <p>However, the myMap is shared by multiple thread, which can be adding, removing from the ConcurrentHashMap at the same time.</p>
  
  <p>How can I make sure the for loop above is thread safe to run? There is not requirement that the loop has to remove all the entries in the map. The loop only needs to remove all the elements at the time myMap.keySet() is called. Any subsequent elements added to the map does not have to be removed.</p>
  
  <p>Obviously I can lock the entire for loop and prevents other thread from touching the map, but I think it is not performance efficient. </p>
  
  <p>Can someone please share your opinion?</p>
  
  <p><strong>EDIT1</strong> : And How about this? Is this thread safe?</p>
  
  <pre><code>for(MyConnection connection : myMap.values()) {
      connection.close();
      myMap.remove(connection.getId());
  }
  </code></pre>
  
  <p>Each connection object has a ID, which is also the key of that entry. </p>