等待一批期货完成时超时? [英] Timeout while waiting for a batch of Futures to complete?

查看:63
本文介绍了等待一批期货完成时超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组Futures,是通过将Callable提交给Executor创建的.伪代码:

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)))

现在,我希望所有期货最多等待n秒,直到全部完成.我知道我可以打电话给Future#get(timeout),但是如果我为一个循环中的所有期货顺序地打电话给Future#get(timeout),那么这些基准就会开始累加起来.伪代码:

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会超时,直到结果就绪为止.因此,如果第一个在超时之前完成,第二个也在超时之前完成,依此类推,则整个执行时间最多为number of futures * timeout而不是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.

因此,我正在寻找一种方法,该方法接受Future列表和超时,所有方法并行运行,然后返回将来结果的集合.有什么想法吗?

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?

推荐答案

您可以使用

You can use ExecutorService.invokeAll:

执行给定的任务,并在所有任务完成或超时到期时(以先发生者为准)返回持有其状态和结果的期货列表.对于返回列表的每个元素,Future.isDone()为true.返回时,尚未完成的任务将被取消.请注意,已完成的任务可能已正常终止,也可能会引发异常而终止.如果在进行此操作时修改了给定的集合,则该方法的结果是不确定的.

Executes the given tasks, returning a list of Futures holding their status and results when all complete or the timeout expires, whichever happens first. Future.isDone() is true for each element of the returned list. Upon return, tasks that have not completed are cancelled. Note that a completed task could have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection is modified while this operation is in progress.


如果您已经有需要监视的Future并且不能使用invokeAll,则可以自己测量超时.伪代码:


If you already have Futures that you need to monitor and can't use invokeAll, you can simply measure the timeout yourself. Pseudo code:

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

这样,您最多可以给每个未来一个持续时间,直到达到超时为止.

This way you give each future at most the duration that is left until you reach your timeout.

这篇关于等待一批期货完成时超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆