0

I am using an ExecutorService to submit my Callable tasks and get Future objects from them.

My question is: can I submit a new task to the executor that needs the result of a future object from an other task completion?

while (someCondition){

                Future<Type1> f1 = executor.submit(new SomeCallable1(Type1_istance));

                try {

                    Future<Type2> f2 = executor.submit(new SomeCallable2(f1));

                } catch (InterruptedException | ExecutionException e) {
                    ...
                }

SomeCallable2 is like:

public void call(){ Type1 a = f1.get(); ...; //use a somehow }

the thread running SomeCollable2 call() should sleep until f1 is ready, right?

A lot of exception raised when i tried my code and I don't understand if they're because I am using Futures in the wrong way or not.

Cordair
  • 63
  • 1
  • 9
  • Don't sleep -- instead use a call back mechanism. – Hovercraft Full Of Eels Jan 15 '16 at 01:48
  • but the javadoc says: get() - Waits if necessary for the computation to complete, and then retrieves its result. – Cordair Jan 15 '16 at 01:53
  • That's exactly right, and that's why you shouldn't call get until the thread is done -- else if you're just going to call get and freeze this thread until the future is done, why even use a background thread in the first place since that totally obliterates any benefit from trying to use a background thread? – Hovercraft Full Of Eels Jan 15 '16 at 01:56
  • See duplicate question to see exactly what I mean. – Hovercraft Full Of Eels Jan 15 '16 at 02:02
  • because, on a single input, i have to make two different computations sequentially (input -> task1 -> output1 -> task2 -> output2 ). I wanted to decouple those tasks, that's why i would use background threads. task2 is separated to task1, and should begin when output1 is ready. with a lot of inputs, this should enhance the parallelism. thanks for the suggestion – Cordair Jan 15 '16 at 02:14
  • I know what you want to do. Again, use a call back such as a PropertyChangeSupport object with a PropertyChangeListener, or with your own created interface if you choose, you get the result from the first Future and use it to load your second Callable, load it into the ExecutorService, and get the 2nd Future. – Hovercraft Full Of Eels Jan 15 '16 at 02:16

0 Answers0