How does Java – callable work under the hood? How do callable objects return values?
I'm trying to understand how callable returns a value when running on another thread
I'm looking at the classes executors, abstractexecutorservice, ThreadPoolExecutor and futuretask, all of which are in Java util. Provided in the concurrent package
You can create an executorservice object by calling a method in executors (for example, newsinglethreadexecutor()) You can then use executorservice Submit (callable C) passes a callable object
Since the call () method is run by the thread provided by executorservice, where does the returned object "jump" to the callback thread?
Take a 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 do I return an integer from a call method run by a separate thread to an integer object (line 3) so that it can be used by system. Net in the main thread (line 7) Print out statement?
Whether the main thread can be run before the executorservice runs its thread so that the system Out statement outputs null?
Solution
ExecutorService. Submit (...) does not return the object from call (), but it returns future < integer > and you can use future Get () method to get the object See the example code below
No, the future get () method will wait until the job is completed If call () returns null, get () otherwise returns (and prints) 10 guarantees
Future<Integer> future = executor.submit(new Callable<Integer>(){ public Integer call() throws Exception { return 10; } }); try { // get() waits for the job to finish before returning the value // it also might throw an exception if your call() threw Integer i = future.get(); ... } catch (ExecutionException e) { // this cause exception is the one thrown by the call() method Exception cause = e.getCause(); ... }