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:

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

Table Of Contents