When is the call () method called in the Java Executor using Callable objects?

This is the sample code from the example . What do I need to know when call() is called on the called? What causes this?

 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); } } 
+6
java concurrency
source share
3 answers

Once you have submitted called, the performer will pay for the call to execute. Depending on the artist, this can happen directly or when the stream becomes available.

The get call on the other hand only waits for the result of the calculation.

So, to be precise: somewhere between the called submit and the get call are returned, the called is called.

+9
source share

The whole idea of ​​using Executor is that it doesn't matter to you exactly when the method is called.

The only thing that is generally guaranteed is that the method will be executed when get() returned from Future .

When exactly it will be called depends on which Executor you use. When using the fixed thread pool that you use in this example, the call() method will be called as soon as there is a free thread, and no other task will face the given task in the queue (provided that there are enough tasks, you will have calls to the < call() methods, which will be executed at any time in your example).

+3
source share

The answer to the question "when will it be displayed during the schedule" is located in java.util.concurrent.ThreadPoolExecutor # to implement the implementation (by default)

0
source share

All Articles