views:

155

answers:

3

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);
  }
}
+3  A: 

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.

Christopher Oezbek
+2  A: 

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).

Joachim Sauer
i understand the issue about threads becoming available at an unpredictable time, i should have asked 'when will a callable be **scheduled** ' - as long as it gets scheduled on *submit()* then that's all i needed to know :)
MalcomTucker
@Malcom: I don't think that that would be a better question, since the scheduling is not visible/observable to the program, so what would change when the if it were scheduled at a later time?
Joachim Sauer
A: 

The answer to "when will a callable be schedules" lies in java.util.concurrent.ThreadPoolExecutor#execute implementation (the default)

Loop