title: Ensure to get all values of `ConcurrentHashMap` when iterating over it while other threads put elements
body: <p>I have a <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html" rel="nofollow noreferrer"><code>ConcurrentHashMap</code></a> that gets filled with <code>put</code> by 8 different Threads. One of the 8 Threads tries to read with a <code>forEach</code> consumer. My problem is, that the <code>ConcurrentHashMap</code> only has 5-7 entries.</p>
  
  <pre><code>map.put(myContent);
  
  ...
  
  map.forEach(element -&gt; ... do something);
  </code></pre>
  
  <p>If I add a <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html#size--" rel="nofollow noreferrer"><code>map.size()</code></a> it for some reason shows all 8 entries</p>
  
  <pre><code>map.put(myContent);
  map.size();
  ...
  map.forEach(element -&gt; ... do something);
  </code></pre>
  
  <p>Going through the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html" rel="nofollow noreferrer"><code>ConcurrentHashMap</code> docs</a> shows that it is not really thread-safe to iterate the map. It is not ensured to get all entries:</p>
  
  <blockquote>
    <p>For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries. Similarly, Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do not throw ConcurrentModificationException. </p>
  </blockquote>
  
  <p>Is it possible to somehow wait or synchronize before I iterate to get absolutly all entries?</p>