简体   繁体   中英

Get the Future with belonging Callable in ExecutorCompletionService

In my application, my tasks implemented Callable are submitted into ExecutorCompletionService and returning Future instance is stored in a List . Then those Future instances are retrieved one by one as following.

        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();
            }   
        }

Here, the output of each AbstractTask is printed which returned from rv = ft.get(); . But I want a way to get the AbstractTask also with the returned value. Is there a way to get the name of Callable (in my case AbstractTask) which returned the value when Future.get() ?

You can just populate a Map<Future<Object>, AbstractTask> that associates each Future with the task that "created" it.

Complete example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM