Note that there are some explanatory texts on larger screens.

plurals
  1. POConcurrently modifying/removing entry from HashMap without iterator
    primarykey
    data
    text
    <p>Some background to the problem: I have a class which is responsible for informing various clients about changes in service. So it the class has several HashMaps of listeners and calls their methods by iterating those HashMaps when needed (it also has methods to add/remove listeners from those HashMaps). The problem is that often I need remove certain listeners while they are being iterated... <strong>and I need to be able to call remove(...) method from outside the loop.</strong> <em>Both iterating and removing are happening on the same thread.</em> Example of the class:</p> <pre><code>class SomeClass { Map&lt;Listener, Boolean&gt; listeners = new HashMap&lt;Listener, Boolean&gt;(); void add(Listener listener) { listeners.put(listener, true); } void remove(Listener listener) { listeners.remove(listener); } void notifyListeners() { Iterator&lt;Map.Entry&lt;Listener, Boolean&gt;&gt; it = listeners.entrySet().iterator(); while (it.hasNext()) { it.next().getKey().onDo(); } } static interface Listener{ void onDo(); }} </code></pre> <p>And the way I want to call remove(...) (and how that fails): </p> <pre><code>final SomeClass someClass = new SomeClass(); Listener a = new Listener(){ @Override public void onDo() { someClass.remove(this); } }; Listener b = new Listener(){ @Override public void onDo() { someClass.remove(this); } }; Listener c = new Listener(){ @Override public void onDo() { someClass.remove(this); } }; someClass.add(a); someClass.add(b); someClass.add(c); someClass.notifyListeners(); // java.util.ConcurrentModificationException </code></pre> <p>Is there any trick to do this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload