title: Using iterator over for-loop in concurrent java app
body: <p><code>class Nodes</code> has <code>getNodes()</code> method, which is <code>not synchronized</code>. But <code>List&lt;Node&gt; nodes</code> - <code>is synchronized</code>. Many threads could be connected to it, changing <code>nodes</code> in it.</p>
  <p>Like this:</p>
  <pre><code>class Nodes {
   List&lt;Node&gt; nodes = Collections.synchronizedList(new ArrayList&lt;Node&gt;() );
  
   public List&lt;Nodes&gt; getNodes() { return nodes; }
   ...
  }
  </code></pre>
  <p>Client code:</p>
  <pre><code>Nodes nodes;
  
  synchronized(nodes) {
  
   for(Node node: nodes.getNodes()) {
    ...
   }
  
  }
  </code></pre>
  <p>I do not have interrogation tests for that, but:</p>
  <p>Should I use <code>while(iterator.hasNext()) { var = iterator.next() }</code> instead of for-loop ?</p>
  <p>Because I know that when I try to delete <code>nodes.remove(node)</code> inside for-loop it fails with <code>ConcurentModificationException</code>.</p>
  <hr />
  <p><strong>EDIT:</strong> (related issue)</p>
  <p>If iterator is good stuff to use, then having this code (client code):</p>
  <pre><code>Iterator&lt;Node&gt; iter = nodes.getNodes().iterator();
  while (iter.hasNext()) {  // line 1
      Node node = iter.next();  // line 2
  }
  </code></pre>
  <p>It is not safe anyway:</p>
  <pre><code> 1. thread1 goes to line 1, hoping that now iter would return him next() value. 
   2. but at that moment thread2 delete that value.
   3. thread1 has Exception and fails.
  </code></pre>
  <p>Does it mean that I should do locking on client side anyway. This is what I don't want to do.</p>
  <p>One of the solutions I have:</p>
  <pre><code>while (iter.hasNext()) {
              
      try {
         Node node = iter.next();
         ...
                    
      } catch (NoSuchElementException ex) {continue;}  // handle exception - do more try
  }
  </code></pre>
  <hr />
  <p><strong>EDIT:</strong></p>
  <p>Answer for my case was: to use <strong>CopyOnWriteArrayList</strong>. I can even stay with <code>for-loop</code> with it.</p>
  <p>But another option: Just return client a copy of the list to let them know whatever they want with it. Because it is kind of strange (inconsistent) providing 'snapshot iterator' AND real data in the list at the same time.</p>