Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
  }
}
like image 222
MalcomTucker Avatar asked Mar 17 '10 11:03

MalcomTucker


2 Answers

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.

like image 104
Christopher Oezbek Avatar answered Oct 06 '22 01:10

Christopher Oezbek


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

like image 29
Joachim Sauer Avatar answered Oct 06 '22 01:10

Joachim Sauer