Java Future ExampleIn 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. Syntax: Example of Java FutureThe 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 InterfaceThe 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 ProgrammingGetting ResultAs 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 TaskWe 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 DoneThe interface provides a method isDone() to check if the asynchronous task is completed or not. For example: Check if an Asynchronous Task is CancelledThe 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 FutureFutureExample.java Output: Next TopicMinimum Cost Path Problem in Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India