When does the call() method get called in a Java Executor using Callable objects?

concurrency, java

Solution

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.

Problem

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

Original source