Java Future Example
In Java, Future is an interface that belongs to java.util.concurrent package. It is used to represent the result of an asynchronous computation. The interface provides the methods to check if the computation is completed or not, to wait for its completion, and to retrieve the result of the computation. Once the task or computation is completed one cannot cancel the computation.
Example of Java Future
The best example of Java Future is ExecutorService interface. It produces a Future (from some of their methods) object for tracking progress of one or more asynchronous task.
Methods of the Future Interface
The interface provides the following five methods:
There was some shortcoming of the Future interface that are as follows:
In order to overcome the above limitations, Java 8 introduced CompletableFuture.
Using Future in Asynchronous Programming
As we have discussed above, the Future represents the result of an asynchronous task. In order to retrieve the result of that asynchronous task, the Java Future interface provides the following two versions of the get() methods both return an object. Note that the return type may be a generic type. For example:
Note: If we try to invoke the get() method before the asynchronous task is completed, the get() method will block until the result is ready.
In order to overcome the above shortcoming, the Future interface provides another version of the get() method that excepts an amount of time (in milliseconds) as a parameter. It represents that the Future will wait for an amount of time to complete the task after that result will be available in the Future. For example:
If Future does not get any result within the specified time, a TimeoutException is thrown by the Future.
Cancel an Asynchronous Task
We can also cancel an asynchronous task at any point by calling the cancel() method of the Future interface. For example:
Check if an Asynchronous Task is Done
The interface provides a method isDone() to check if the asynchronous task is completed or not. For example:
Check if an Asynchronous Task is Cancelled
The Future interface provides a method isCancelled() to check if the asynchronous task represented by Future is cancelled or not. It returns true if the task is cancelled successfully, else returns false. For example:
Example of Java Future
Next TopicMinimum Cost Path Problem in Java