java – 遍历List对象会抛出IndexOutOfBounds异常

我有一个ExecutorService,用于调用Callable集合的obejcts,并返回与集合中Callable元素相对应的Future对象List.

但是,在遍历列表的某个地方,它会引发以下异常:

java.util.concurrent.ExecutionException: java.lang.IndexOutOfBoundsException: Index: 7, Size: 1
at java.util.concurrent.FutureTask.report(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at com.soc.transformcsv.ParallelTransformationPool.doExecute(ParallelTransformationPool.java:91)

我一直在执行的代码是

List<Future<StringBuilder>> futures = executor.invokeAll(builders);
executor.shutdown();
HashMap<String, List<StringBuilder>> allServiceTypeRows = new LinkedHashMap<>();

for (Future<StringBuilder> future : futures) {
    // I have tried putting future.isDone() which always prints true before the exception
    StringBuilder recordBuilder = future.get();
    // do more
}

它在future.get()行给出了错误.

请帮助解决障碍或让我知道我还提供了什么.

解决方法:

即使Callable中存在异常,isDone()的结果也可能为true.从isDone documentation

Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation — in all of these cases, this method will return true.

所以有问题的未来已经完成,但在计算时遇到了错误.在您发布的堆栈跟踪下,应该有另一个,列出“由…引起” – 这将导致您的Callable中的根失败.

例如,请参阅this ideone link的输出.成功检查isDone为true后出现此异常:

Exception in thread "main" java.util.concurrent.ExecutionException: java.lang.RuntimeException: This is a failure!
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:192)
    at Ideone.main(Main.java:16)
Caused by: java.lang.RuntimeException: This is a failure!
    at Ideone$SampleCallable.call(Main.java:21)
    at Ideone$SampleCallable.call(Main.java:19)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at Ideone.main(Main.java:14)
上一篇:了解Java ExecutorService


下一篇:Java并发编程,深度探索J.U.C - AQS