java中遍历对象获取索引,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> futures = executor.invokeAll(builders);

executor.shutdown();

HashMap> allServiceTypeRows = new LinkedHashMap<>();

for (Future 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,future,executorservice,futuretask

来源: https://codeday.me/bug/20190528/1169681.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值