ConcurrentModificationException looping through an ArrayList and deleting elements

Following code throws ConcurrentModificationException  exception :
   List<Connection> connList = new ArrayList<>();
   for (Connection c1 : connList) 
     {
       try
         {
           ((Connection) c1).close();
           connList.remove(c1);
           closedConn++;                    
         }
..
Exception:
java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
    at java.util.ArrayList$Itr.next(ArrayList.java:831)
    at UcpPool.UcpPoolBean.checkSessionInPool(UcpPoolBean.java:786)

Workaround - Using an Iterator when looping through an Arraylist
    Iterator<Connection> connIter = connList.iterator();
    while (connIter.hasNext())
      {
        Connection c1 = connIter.next();     
        try
          {
            ((Connection) c1).close();
            connIter.remove();
            closedConn++;
          }

Leave a Reply

Your email address will not be published. Required fields are marked *