在ExecutorCompletionService中使用属性Callable获取未来

时间:2015-06-21 16:31:06

标签: java

在我的应用程序中,我实施的Callable任务已提交到ExecutorCompletionService,并且返回的Future实例存储在List中。然后逐个检索这些Future实例,如下所示。

        List<Future< Object>> futureList= new ArrayList<Future < Object> >();

        final ExecutorService pool = Executors.newFixedThreadPool( TASK_SIZE );

        final ExecutorCompletionService<Object>  completionService = new ExecutorCompletionService<Object> (pool);
        for ( AbstractTask callable : taskList) {
                futureList.add( completionService.submit(callable) );
        }
        Object rv=null;
        while(futureList.size() > 0) {
            try{
                Future   ft = completionService.take();
                rv = ft.get();
                System.out.println("task returned value : " + rv);
                futureList.remove(ft);
            }catch(Exception e){
                e.printStackTrace();
            }   
        }

这里,打印每个AbstractTask的输出,它从rv = ft.get();返回。但我想要一种方法来获取AbstractTask也返回值。有没有办法获得Callable的名称(在我的情况下是AbstractTask),它在Future.get()时返回了值?

1 个答案:

答案 0 :(得分:1)

您可以填充Map<Future<Object>, AbstractTask>,将每个Future与“创建”它的任务相关联。

完整示例:

public class Tasks {
    public static void main(String[] args) throws InterruptedException {
        ExecutorCompletionService<String> service = new ExecutorCompletionService<String>(Executors.newSingleThreadExecutor());

        List<Callable<String>> callables = new ArrayList<>();
        Map<Future<String>, Callable<String>> map = new HashMap<>();

        for (int i = 0; i < 10; i++) {
            final String name = Integer.toString(i);
            Callable<String> c = new Callable<String>() {
                @Override
                public String call() throws Exception {
                    return name;
                }

                @Override
                public String toString() {
                    return name;
                }
            };
            callables.add(c);

            Future<String> future = service.submit(c);
            map.put(future, c);
        }

        for (int i = 0; i < callables.size(); i++) {
            Future<String> future = service.take();
            Callable<String> correspondingTask = map.get(future);
            System.out.println("correspondingTask = " + correspondingTask);
        }
    }
}