8

I have a set of Futures created by submitting Callables to an Executor. Pseudo code:

for all tasks
  futures.add(executor.submit(new callable(task)))

Now I'd like to get all futures waiting at most n seconds until all complete. I know I can call Future#get(timeout) but if I call that sequentially for all my futures in a loop the timouts start adding up. Pseudo code:

for all futures
  future.get(timeout)

get blocks with a timeout until the result is ready. Therefore, if the first completes just before timeout and the second also completes just before timeout and so on the entire execution time is number of futures * timeout at most instead of timeout.

Hence, I'm looking for a method that accepts a list of Futures and a timeout, runs all in parallel and then returns a collection of future results. Any ideas?

4

1 回答 1

12

您可以使用ExecutorService.invokeAll

执行给定的任务,当全部完成或超时到期(以先发生者为准)时,返回保存其状态和结果的 Futures 列表。Future.isDone()对于返回列表的每个元素都为真。返回时,未完成的任务将被取消。请注意,已完成的任务可能已经正常终止,也可能通过引发异常终止。如果在此操作进行时修改了给定的集合,则此方法的结果是不确定的。


如果你已经有了Future需要监控而不能使用的s invokeAll,你可以简单地自己测量超时时间。伪代码:

long endTime = System.currentTimeMillis() + timeoutMS;
for(f : futures)
    f.get(Math.max(0, endTime - System.currentTimeMillis()), TimeUnit.MILLISECONDS);

这样,您最多可以为每个未来提供直到超时为止的持续时间。

于 2013-07-02T20:31:39.237 回答