首页 > 解决方案 > 为每个循环中的每个对象调用方法时出现 ConcurrentModificationException

问题描述

我目前正在构建一个购物车,我想在结帐后为我的购物车中的每个项目更新我的数据库中的项目库存。

这些项目作为 Java Bean 列表存储在 Session Scope 中。这是我的结帐 servlet。

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

    final HttpSession session = request.getSession();
    @SuppressWarnings("unchecked")
    List<CartItems> itemsInWc = (List<CartItems>) session.getAttribute("Cart");

    for (CartItems item : itemsInWc) {
        updateBestand(item.getInCart(), item.getSize(), item.getId(), item.getKat(), item.getName(), item.getBestand());
    }
}

首先,我得到包含项目的列表,然后我遍历eatch 项目并使用“updateBestand”方法更新库存。

public void updateBestand(int inCart, String size, int id, String kategorie, String name, int bestand)
                throws ServletException, IOException {
    
    int updateAnzal = bestand - inCart;

    try (Connection con = ds.getConnection();
                    PreparedStatement pstmt = con.prepareStatement("UPDATE " + kategorie + " SET " + size + " =?"
                                    + " WHERE artikelName = ? and id = ?")) {

        pstmt.setInt(1, updateAnzal);
        pstmt.setString(2, name);
        pstmt.setInt(3, id);

        pstmt.executeUpdate();

    } catch (Exception ex) {
        throw new ServletException(ex.getMessage());

    }

}

但是每次我调用我的 checkOut-Servlet 时,它只会更新列表中第一个项目的库存,然后引发 ConcurrentModificationException。

java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at Servlets.UpdateBestandServlet.doGet(UpdateBestandServlet.java:40)

标签: javaconcurrentmodification

解决方案


推荐阅读