Java 访问Executor服务未来列表时的ConcurrentModificationException

Java 访问Executor服务未来列表时的ConcurrentModificationException,java,collections,concurrentmodification,Java,Collections,Concurrentmodification,我正在尝试使用executor服务发出并行请求。完成后,我将使用Java 7中的以下代码访问未来。我只是想把它存储在一个名为infos的新列表中。我看到ConcurrentModificationException异常。有没有关于如何摆脱它的建议 List<Info> infos = new ArrayList<>(); for(Future<Info> fut : list){ try {

我正在尝试使用executor服务发出并行请求。完成后,我将使用Java 7中的以下代码访问未来。我只是想把它存储在一个名为
infos
的新列表中。我看到
ConcurrentModificationException
异常。有没有关于如何摆脱它的建议

        List<Info> infos = new ArrayList<>();
        for(Future<Info> fut : list){
            try {
                infos.add(fut.get()); // ConcurrentModificationException happening here...
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
        // send infos
List infos=new ArrayList();
对于(未来未来:列表){
试一试{
infos.add(fut.get());//此处发生ConcurrentModificationException。。。
}捕获(中断异常|执行异常e){
e、 printStackTrace();
}
}
//发送信息
更新-

private List<Future<Info>> list;

    Future<Info> future = executor.submit(callable);
    list.add(future);
私有列表;
未来=执行人提交(可调用);
增加(未来);

您的列表类型为
Future
,而在增强for循环中,您使用的是Info

 for(Future<Info> fut : list)
用于(未来未来:列表)
您的代码应该是:

    private List<Future<Info>> list = new ArrayList<>();
    Future<Info> future = executor.submit(callable);
    list.add(future);
private List=new ArrayList();
未来=执行人提交(可调用);
增加(未来);

什么是
列表
?您确定
ConcurrentModificationException
发生在该行代码中吗?无论是
add(…)
还是
get()
都不会引发该异常。如果循环运行时不同的线程修改了
list
,则
for
循环本身可能会发生变化,这取决于
list
的属性。我正在将所有未来添加到列表中。所以我们需要将for循环更改为iterator?for循环是一个
迭代器
循环。这就是为什么它可以抛出异常,因为迭代器和子列表几乎是该特定异常的唯一原因。也许,您会感到困惑,因为
Future.get
抛出
ExecutionException
包装后台任务中发生的异常?是,我在更改它的类型时犯了一个错误。现在我已经改正了。但这不是问题所在。