Java Future

In multithreaded programming, Java Future with Callable is very important for tasks which we want to know status and get the returned object.

This article give us an example for how to work with Future and Callable inside.

Related Articles:
Java Thread Pool – ExecutorService
Java 8 CompletableFutures
Java 8 CompletableFuture Handle Exception
Java 8 Multiple CompletableFutures

I. Introduction
1. Callable

The Callable interface is similar to Runnable, which are designed for classes’ instances executed by thread. However, Callable can return a result and throw a checked exception.

We execute Callable in a thread pool by using an Executor, which provides methods to manage termination or produce a Future for asynchronous tasks.

2. Future

Executor submit method with Callable as parameter return a Future object:

A Future represents the result of an asynchronous computation. It has methods to check completion, or wait for completion.
The result of the completion can be retrieved using method get when it completes, and is blocked until it is ready.

The V get(...) method will throws:
CancellationException if the computation was cancelled
ExecutionException if the computation threw an exception
InterruptedException if the current thread was interrupted while waiting
TimeoutException if the wait timed out

II. Example

Check results in Console Screen:

By grokonez | December 12, 2016.

Last updated on June 4, 2017.

Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *