This is some sample code from an example. What I need to know is when call()
gets called on the callable? What triggers it?
public class CallableExample {
public static class WordLengthCallable
implements Callable {
private String word;
public WordLengthCallable(String word) {
this.word = word;
}
public Integer call() {
return Integer.valueOf(word.length());
}
}
public static void main(String args[]) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(3);
Set<Future<Integer>> set = new HashSet<Future<Integer>>();
for (String word: args) {
Callable<Integer> callable = new WordLengthCallable(word);
Future<Integer> future = pool.submit(callable); //**DOES THIS CALL call()?**
set.add(future);
}
int sum = 0;
for (Future<Integer> future : set) {
sum += future.get();//**OR DOES THIS CALL call()?**
}
System.out.printf("The sum of lengths is %s%n", sum);
System.exit(sum);
}
}
Once you have submitted
the callable, the executor will schedule the callable for execution. Depending on the executor this might happen directly or once a thread becomes available.
Calling get
on the other hand only waits to retrieve the result of the computation.
So to be precise: Somewhere in-between submit
being called and the call to get
returning, the callable is called.
The entire idea of using an Executor
is that you shouldn't care when exactly the method is called.
The only thing that is guaranteed in general is that the method will have executed when get()
of the Future
returns.
When exactly it will be called depends on which Executor
you use. With the fixed thread pool you use in the example, the call()
method will be called as soon as there is a free thread and no other task is in front of the given task in the queue (so as long as there are enough tasks, you'll have 3 call()
method calls running at any given time in your example).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With