【发布时间】:2018-04-13 20:02:53
【问题描述】:
此问题类似于以下现有问题。我知道IndexOutOfBoundsException 是RuntimeException,因此很明显代码中存在错误。
traversing a List<Future> object throws IndexOutOfBounds exception
在我的例子中,这个异常实际上发生在实际传输文件的 API 中。它在 call() (Lambda) 中被捕获,并被视为 失败 进行重试。
java项目中有各种文件传输任务。因此我使用ExecutorService 来满足要求。
有一个文件列表,每个文件将从这些文件中提供给ExecutorService,我在其中传递一个 Callable,如果传输失败,它最终会返回文件对象。 p>
我知道我一定做错了什么。
请建议需要进行哪些更改,非常感谢您的时间。
如果需要任何其他信息,请告诉我。
(真实的类和方法名替换为虚拟名)
异常堆栈跟踪
java.util.concurrent.ExecutionException: java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at FileTransfer.lambda$transfer$1(FileTransfer.java)
at java.util.ArrayList.forEach(ArrayList.java:1249)
at FileTransfer.transfer(FileTransfer.java)
Caused by: java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
at java.util.LinkedList.checkElementIndex(LinkedList.java:555)
at java.util.LinkedList.get(LinkedList.java:476)
at com.autofixrt.errorhandler.strategy.retry.FileTransfer.lambda$transfer$0(FileTransfer.java)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
以下是进行文件传输操作的java方法。
FileTransfer.java
public class FileTransfer {
public boolean transfer(List<File> fileList) {
final int size = fileList.size();
final int[] pos = {0};
// Also tried with AtomicInteger but gives the same IndexOutOfBoundsException
final ExecutorService executor = ExecutorUtil.createDefaultExecutor();
final List<Future<File>> futureList = new ArrayList<>();
try {
while (pos[0] < size) {
final Future<File> future = executor.submit(() -> {
File failed = null;
// Exception caused by at below line
// Caused by: java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
final File input = fileList.get(pos[0]++); // caused by
try {
final boolean isSuccess = // API call to transfer file;
if (!isSuccess)
failed = input;
} catch (final Exception e) {
failed = input;
}
return failed;
}); // submit ends
futureList.add(future);
} // while ends
final List<File> failedList = new ArrayList<>(0);
// iterate over list of futures collected above
futureList.forEach(f -> {
try {
// java.util.concurrent.ExecutionException: java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
final File input = f.get(); // Exception occures at this line
if (input != null)
failedList.add(input);
} catch (Exception e) {
System.out.println("Error in retrieving failed from future");
e.printStackTrace();
}
});
} finally {
ExecutorUtil.shutdown(executor);
futureList.clear();
}
boolean success = true;
// send failed email, if still failed present
if (!isEmpty(failed)) {
success = false;
// sendErrorEmail(failedList);
}
return success;
}
}
ExecutorUtil.java
public final class ExecutorUtil {
private ExecutorUtil() { }
private static final int DEFAULT_THREAD_POOL_SIZE = Runtime.getRuntime().availableProcessors() * 2;
public static ExecutorService createDefaultExecutor() {
return createExecutor(DEFAULT_THREAD_POOL_SIZE);
}
private static ExecutorService createExecutor(int threadPoolSize) {
return Executors.newFixedThreadPool(threadPoolSize);
}
public static void shutdown(ExecutorService executor) {
if (isNull(executor))
return;
executor.shutdown(); // Disable new tasks from being submitted
try {
// Wait 20 seconds for existing tasks to terminate
if (!executor.awaitTermination(20L, TimeUnit.SECONDS)) {
executor.shutdownNow(); // Cancel currently executing tasks
// Wait 10 seconds for tasks to respond to being cancelled
if (!executor.awaitTermination(10L, TimeUnit.SECONDS))
System.out.println("Pool did not terminate");
else
System.out.println("Thread pool has been shutdown");
} else
System.out.println("Thread pool has been shutdown - no await");
} catch (InterruptedException e) {
// (Re-)Cancel if current thread also interrupted
executor.shutdownNow();
}
}
}
【问题讨论】:
-
为什么不使用 foreach 循环而不是这个丑陋的 while(pos[0]) 循环?
-
这个
int[]作为可变int的持有者是一个完整的反模式,您的错误与糟糕的编程实践以及检查变量并更新它的格式错误的逻辑直接相关一开始是一种非原子方式。 -
感谢您的宝贵时间和 cmets。我已经编辑了这个问题,以证明它与重复有什么不同。同样在 cmets 中,我已经提到我尝试使用 AtomicInteger,但没有解决此错误。
-
将 while 循环替换为 foreach 最初确实解决了问题。似乎很早就确认了。
标签: java multithreading future executorservice callable