EDIT: I understand my mistake. I don't why but I was thinking that after the `previousItems.add(p);` is executed it was going out from the `for loop`. I've solved by adding a `break`

Other questions about this Exception didn't help me to get a solution. 

I have a `Servlet` that is called when I add an item in the cart from another page. 

I have an `ArrayList<Product>` and I iterate through the List to check if the same Product that I'm trying to add in already in the list. If it's already there I update its quantity otherwise I add the new Product in the List. 

Everything is fine if add always the same Product, the Exception occurs when I add a different Product. So I think the problem in the code is after the `else` (commented with "This"), because it's executed if the Product is different.

```
@WebServlet(name = "AddCart", urlPatterns = {"/AddCart"})
public class AddCart extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        ArrayList<Product> previousItems = (ArrayList<Product>) session.getAttribute("previousItems");
        Product p = (Product) session.getAttribute("currentProduct");
        if (previousItems == null) {
            previousItems = new ArrayList<Product>();
        }

            if (p != null) {
                if (previousItems.size()>0) {
                    for (Product p1 : previousItems) {
                        if (p1.getId() == p.getId()) {
                            p1.addQuantity();
                        } else { //This
                            previousItems.add(p);
                        }
                    }
                } else {
                    previousItems.add(p);
                }
            }

        session.setAttribute("previousItems", previousItems);
        response.sendRedirect("cart.jsp");
    }
}

```

I've also tried to remove the `synchronized` same Exception.

And this is the `HTTP Status 500 – Internal Server Error`

> 
> java.util.ConcurrentModificationException
> 
> 
> 
> > 
> > java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
> >  java.util.ArrayList$Itr.next(ArrayList.java:851)
> >  servlets.AddCart.doGet(AddCart.java:36)
> >  javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
> >  javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
> >  org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
> > 
> > 
> > 
> 
> 
>