How does a Callable work under the hood? How is it possible for a callable object to return a value?

Viewed 1964

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?

2 Answers
Related