title: Understanding collections concurrency and Collections.synchronized*
body: <p>I learned yesterday that I've been incorrectly using collections with concurrency for many, many years.</p>
  
  <p>Whenever I create a collection that needs to be accessed by more than one thread I wrap it in one of the Collections.synchronized* methods. Then, whenever <em>mutating</em> the collection I also wrap it in a synchronized block (I don't know why I was doing this, I must have thought I read it somewhere).</p>
  
  <p>However, after reading the API more closely, it seems you need the synchronized block when <em>iterating</em> the collection.  From the API docs (for Map):</p>
  
  <blockquote>
    <p>It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views:</p>
  </blockquote>
  
  <p>And here's a small example:</p>
  
  <pre><code>List&lt;O&gt; list = Collections.synchronizedList(new ArrayList&lt;O&gt;());
  ...
  synchronized(list) {
     for(O o: list) { ... }
  }
  </code></pre>
  
  <p>So, given this, I have two questions:</p>
  
  <ul>
  <li><p>Why is this even necessary?  The only explanation I can think of is they're using a default iterator instead of a managed thread-safe iterator, but they could have created a thread-safe iterator and fixed this mess, right?</p></li>
  <li><p>More importantly, what is this accomplishing?  By putting the iteration in a synchronized block you are preventing multiple threads from iterating at the same time.  But another thread could mutate the list while iterating so how does the synchronized block help there?  Wouldn't mutating the list somewhere else screw with the iteration whether it's synchronized or not? What am I missing?</p></li>
  </ul>
  
  <p>Thanks for the help!</p>