title: Iterable java list roundrobin concurrency issues
body: <p>I have several cases where I need to set up a <code>List</code> and then Iterate over them in a roundrobin fashion.  I am relatively new to multi threading so I am learning as I go.</p>
  
  <p>Today I started getting some concurrency issues.</p>
  
  <pre><code>Exception in thread "LogThing: 25" Exception in thread "LogThing: 27" Exception in thread "LogThing: 21" java.util.ConcurrentModificationException
      at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
      at java.util.ArrayList$Itr.next(ArrayList.java:851)
      at com.google.common.collect.Iterators$2.next(Iterators.java:418)
      at com.example.my.RoundRobinIterable.getNext(RoundRobinIterable.java:22)
      at com.example.my.EpsSendingStrategy.run(EpsSendingStrategy.java:22)
      at java.lang.Thread.run(Thread.java:745)
  </code></pre>
  
  <p>Now the RoundRobbinIterable is quite simple.</p>
  
  <pre><code>import java.util.Iterator;
  import java.util.List;
  
  import com.google.common.collect.Iterables;
  
  public class RoundRobinIterable&lt;T&gt; {
    private final Iterator&lt;T&gt; elements;
  
    public RoundRobinIterable(final List&lt;T&gt; elements) {
      this.elements = Iterables.cycle(elements).iterator();
    }
  
    public synchronized T getNext() {
      return this.elements.next();;
    }
  
  }
  </code></pre>
  
  <p>Now EpsSendingStrategy.java has a <code>static RoundRobinIterable&lt;PrintWriter&gt; writerIterable</code> and as you can see from the stacktrace it is also a thread.  When I create my <code>RoundRobinIterable</code> I pass in  <code>Collections.synchronizedList(new ArrayList&lt;&gt;())</code> with some values.  Line 22 happens to be <code>writer = writerIterable.getNext();</code></p>
  
  <p>So somehow <code>getNext()</code> is causing a <code>java.util.ConcurrentModificationException</code> exception</p>
  
  <p>EDIT 1:</p>
  
  <pre><code>public class EpsSendingStrategy extends SendingStrategy {
  
    public EpsSendingStrategy(LogDosSettings settings) {
      super(settings);
      logger = LogManager.getLogger(EpsSendingStrategy.class);
    }
  
    @Override
    public void run() {
      createConnections();
      startSending.set(System.nanoTime());
      PrintWriter writer;
  
      while (sendMessages) {
        logger.debug("about to write message");
        writer = writerIterable.getNext();
        writer.println(settings.getMessage());
        writer.flush();
  
        lastSent.set(startSending.get() + logItoration.get() * 1000000000L / settings.getEps());
        while (System.nanoTime() &lt; lastSent.get());
  
        logItoration.incrementAndGet();
      }
    }
  
  }
  </code></pre>
  
  <p>Edit 2: I also tried the same synchronization used on <a href="https://stackoverflow.com/a/4493759/2599884">https://stackoverflow.com/a/4493759/2599884</a> but this was also a bust.  There is something deeper that I am not understanding.</p>