I am trying to understand how a Callable is able to return a value when it is run on a different thread.
I am looking in the classes Executors, AbstractExecutorService, ThreadPoolExecutor and FutureTask, all available in java.util.concurrent package.
You create an ExecutorService object by calling a method in Executors (e.g. newSingleThreadExecutor()). Then you can pass a Callable object with ExecutorService.submit(Callable c).
Since the call() method is run by a thread provided by the ExecutorService, where does the returned object “jump” back to the calling thread?
Look at this simple example:
1 ExecutorService executor = Executors.newSingleThreadExecutor();
2 public static void main(String[] args) {
3 Integer i = executor.submit(new Callable<Integer>(){
4 public Integer call() throws Exception {
5 return 10;
6 }
7 }).get();
8 System.out.print("Returns: " + i + " Thread: " + Thread.currentThread.getName());
9 // prints "10 main"
10 }
How is it possible that the integer in the call method, which is run by a separate thread, is returned to the Integer object (row 3) so it can be printed by the System.out statement in the main thread (row 7)?
Isn´t it possible for the main thread to be run before the ExecutorService has run its thread, so that the System.out statement prints null?
ExecutorService.submit(...)does not return the object fromcall()but it does return aFuture<Integer>and you can use theFuture.get()method to get that object. See the example code below.No, the
get()method on the future waits until the job finishes. Ifcall()returned null thenget()will otherwise it will return (and print)10guaranteed.