When do lists, collections etc throw a java.util.ConcurrentModificationException in Java?
<p>The following code uses a simple list and displays elements contained in the list through a foreach loop and again through a while loop.</p>

<pre><code>final public class Main
{
    public static void main(String... args)
    {           
        List&lt;String&gt;list=new ArrayList&lt;String&gt;();

        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");

        for(Object o:list)
        {
            System.out.printf("\n"+o);
        }

        Iterator&lt;String&gt;listIterator=list.iterator();

        //list.add("E");   If uncommented, throws an exception.
        //list.add("F");

        while(listIterator.hasNext())
        {
            System.out.printf("\n"+listIterator.next());
        }
    }
}
</code></pre>

<hr>

<p>When the commented two lines above the while loop are uncommented, it throws an exception <code>java.util.ConcurrentModificationException</code>. If those commented lines are placed above this line <code>Iterator&lt;String&gt;listIterator=list.iterator();</code>, it works well.  Such exceptions are very common while handling entities in <strong>EJBs</strong>. Why does this happen? How can it be avoided?</p>
