enigma
enigma

Reputation: 41

Can we get the Callable object from a Future object in Java?

I have a list of callable objects , which I am using to generate a list of future objects. I am using ExecutorService to get the Callable tasks done concurrently and storing the result as list of Future objects. Now I want to know, is there a way so I can get the original callable object which was used to generate a given future object.

Upvotes: 2

Views: 1860

Answers (2)

Reza
Reza

Reputation: 1546

The default implementation doesn't give you this functionality though you can create your own callable

   import org.apache.commons.math3.util.Pair;

    class MyCallable implements Callable<Pair<Callable,MyObject>>{

        private MyService service;
        public String name;
        public MyCallable(MyService srevice,String name){
            this.srevice = srevice;
            this.name = name;

        }

        @Override
        public Pair<Callable,MyObject> call() throws Exception {
            return new Pair(this,service.doSomeStuff())
        }
    }

Now when you invoke the callable object in your future, you will have access to the callable object. Something like future.get().getFirst().name will work.

Upvotes: 0

Frank Neblung
Frank Neblung

Reputation: 3175

If you obtain your Futures by calling ExecutorService.invokeAll() you can rely on the order as is documented in the javadoc.

 * @return a list of Futures representing the tasks, in the same
 *         sequential order as produced by the iterator for the
 *         given task list, each of which has completed

Upvotes: 1

Related Questions