Retrieving value from computation - Callable

suggest change

If your computation produces some return value which later is required, a simple Runnable task isn’t sufficient. For such cases you can use ExecutorService.submit(Callable<T>) which returns a value after execution completes.

The Service will return a Future which you can use to retrieve the result of the task execution.

// Submit a callable for execution
ExecutorService pool = anExecutorService;
Future<Integer> future = pool.submit(new Callable<Integer>() {
    @Override public Integer call() {
        //do some computation
        return new Random().nextInt();
    }
});    
// ... perform other tasks while future is executed in a different thread

When you need to get the result of the future, call future.get()

try {
    // Blocks current thread until future is completed
    Integer result = future.get(); 
catch (InterruptedException || ExecutionException e) {
    // handle appropriately
}
try {
    // Blocks current thread for a maximum of 500 milliseconds.
    // If the future finishes before that, result is returned,
    // otherwise TimeoutException is thrown.
    Integer result = future.get(500, TimeUnit.MILLISECONDS); 
catch (InterruptedException || ExecutionException || TimeoutException e) {
    // handle appropriately
}

If the result of a scheduled or running task is no longer required, you can call Future.cancel(boolean) to cancel it.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Executor, ExecutorService and Thread pools:
* Retrieving value from computation - Callable

Table Of Contents
8 Arrays
10 Maps
11 Strings
23 Executor, ExecutorService and Thread pools
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap