Java并发:如何在处理过程中告诉哪个Future属于哪个Callable?

时间:2012-04-24 19:38:23

标签: java concurrency future executorservice callable

我有一组Callables和一个ExecutorService。当我调用所有时,我得到一个Future对象列表。如何在Future完成之前判断哪个Future对象映射到哪个Callable?我之后可以说是因为

代码:

 ExecutorService es = .....;

 Collection<Callables> uniqueCallables = .....;  // each Callable is unique!

 List<Future> futures = es.invokeAll(uniqueCallables);

 // TODO--find unique Future A which is the future for Callable A!

2 个答案:

答案 0 :(得分:9)

根据Java referenceinvokeAll(uniqueCallables)List<Future>中的订单保留为uniqueCallables.iterator()生成的订单:

  

<强>返回:   代表任务的期货清单,同样如此   由给定任务列表的迭代器生成的顺序,   每个都已完成。

答案 1 :(得分:4)

听起来你只需要能够从Future查找原始的callable。如果你没有使用invokeAll,你可以修饰包含submit()的Executor来创建一个ContextualFuture,它保留对原始callable的引用。

/*pseudo example*/
class ContextualFuture<RETURN> implements Future<RETURN> {
   private Callable<RETURN> callable;
   private Future<RETURN> wrappedFuture;
   public ContextualFuture(Callable<RETURN> callable, Future<RETURN> future){
       this.callable = callable;
       this.future = future;
   }
   // implemented/wrapped methods 
}

class ContextualThreadPool {
   private ExecutorService wrappedExecutor;
   public <T> ContextualFuture<T> submit(Callable<T> task){
       Future<T> f = wrappedExecutor.submit(task);
       return new ContextualFuture<T>(task, f);
   }
}