当前位置: 代码迷 >> 综合 >> 关于集合中线程不安全解决办法,Exception in thread “Thread-2“ java.util.ConcurrentModificationException
  详细解决方案

关于集合中线程不安全解决办法,Exception in thread “Thread-2“ java.util.ConcurrentModificationException

热度:5   发布时间:2024-03-07 22:36:26.0

报错代码:

new Thread(()->{while (activeConn.size()>0){activeConn.forEach(conn->{if (conn.hasNewRequest()){Future<HttpRequest> future1 = pool.submit(conn);try {HttpRequest httpRequest = future1.get();System.out.println("当前请求报文为:"+httpRequest);FileResource fileResource1 = new FileResource();fileResource1.setConn(conn.getConn());fileResource1.setRequest(httpRequest);pool.submit(fileResource);} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();}}});}
}).start();

报错原因:我在监听的一个list里不断进行修改,添加和删除操作。
修改为:
Collections.synchronizedList(new ArrayList<>())
但是这样效率较低。
试了一下其他容器
ConcurrentHashMap

  相关解决方案