Iterate over ConcurrentHashMap while deleting entries
<p>I want to periodically iterate over a <code>ConcurrentHashMap</code> while removing entries, like this:</p>

<pre><code>for (Iterator&lt;Entry&lt;Integer, Integer&gt;&gt; iter = map.entrySet().iterator(); iter.hasNext(); ) {
    Entry&lt;Integer, Integer&gt; entry = iter.next();
    // do something
    iter.remove();
}
</code></pre>

<p>The problem is that another thread may be updating or modifying values while I'm iterating. If that happens, those updates can be lost forever, because my thread only sees stale values while iterating, but the <code>remove()</code> will delete the live entry.</p>

<p>After some consideration, I came up with this workaround:</p>

<pre><code>map.forEach((key, value) -&gt; {
    // delete if value is up to date, otherwise leave for next round
    if (map.remove(key, value)) {
        // do something
    }
});
</code></pre>

<p>One problem with this is that it won't catch modifications to mutable values that don't implement <code>equals()</code> (such as <code>AtomicInteger</code>). Is there a better way to safely remove with concurrent modifications?</p>