【发布时间】:2018-04-25 13:28:52
【问题描述】:
我正在使用 ExecutorService 提交一批任务。我正在这样做:
ListeningExecutorService exec = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(threads));
List<ListenableFuture<Whatever>> futures = new ArrayList<>();
for (int i = 0; i < 100; i++) {
results.add(exec.submit(new MyTask(i)));
}
ListenableFuture<List<Whatever>> listListenableFuture = Futures.successfulAsList(futures);
try {
List<Whatever> responses = listListenableFuture.get(2000, TimeUnit.MILLISECONDS);
for (Whatever response : responses) {
LOG.info("Yay!");
}
} catch (TimeoutException e) {
LOG.info("Timeout Exception");
} catch (Exception e) {
// Nay!
}
这里的问题是 - 如果其中一项任务花费的时间超过 2000 毫秒,则会抛出 TimeoutException,尽管某些任务可能已经完成,但我将在响应中一无所获。
所以我想检索已完成的任务的响应(无论是部分还是完整),直到超时(2000 毫秒)。例如:
(相对于批处理调用的 START_TIME 的时间)
任务 1:1000 毫秒
任务 2:3000 毫秒
任务 3:1800 毫秒
输出:
超时异常
期望的输出:
耶! 耶!
我想到的一个解决方案是单独获取期货并将它们的超时设置为MAX(0, TIME_OUT - TIME_NOW - START_TIME)。这可能有效,但对我来说似乎不是一个干净的解决方案。
【问题讨论】:
标签: java multithreading concurrency executorservice callable