title: Concurrent collection of listeners
body: <p>I am dealing with some problem. I found a solution that works, but I'm still confused and think that there is a better one.</p>
  
  <p>I have model class with collection of listeners of type let's say IListener. Other classes are allowed to add or remove listener via public methods.</p>
  
  <p>My model class uses 2 threads to update some data and after this process is finished, listeners are notified about model changes.</p>
  
  <p>So code goes like this</p>
  
  <pre><code>void updateThread1() {
      synchronized (lock) {
          updateLogic();
          List&lt;IListener&gt; listenersCopy = new ArrayList&lt;&gt;(listeners);
          for (IListener listener : listenersCopy) {
               listener.dataUpdated();
          }
      }
  
  void updateThread2() {
      synchronized (lock) {
          updateLogic2();
          List&lt;IListener&gt; listenersCopy = new ArrayList&lt;&gt;(listeners);
          for (IListener listener : listenersCopy) {
               listener.dataUpdated();
          }
      }
  </code></pre>
  
  <p>And here is my problem: as listeners can be added or removed by different threads then updateThread1 and updateThread2 so there is a pretty good chance to get ConcurrentModificationException.</p>
  
  <p>I can't tell whether creating copy of array is atomic (i.e. ArrayList#addAll() uses some native array copy mechanizm).</p>
  
  <p>I tried to used CopyOnWriteArrayList, which works fine. Second approach was to use concurrent hash set (from Collections#newSetFromMap()) that was backed by ConcurrentHashMap.</p>
  
  <p>This works for me, but I'd like to know whether there are some design approaches to make it work.</p>
  
  <p>I'd appreciate any help. Thanks.</p>