How to get the result of a Future in Java
What is Future in Java?
The executor service’s submit() method submits a task to a thread for execution. However, it does not know when the task’s outcome will be available. As a result, it returns a Future. This is a reference that can be used to retrieve the task’s outcome when it becomes available.
In other languages, such as JavaScript, the idea of a Future is similar to a Promise. It reflects the outcome of a calculation that will be completed at a later date.
Hence, a Future is a placeholder that stores the result of an asynchronous computation.
The get() method
The get() method is a blocking call. It is used to wait for the processing of the task to finish and retrieve the result.
Syntax
V get()
Parameters
The method has no parameters.
Return value
This method returns the result of the computation.
Code
import java.util.concurrent.*;public class Main {public static void main(String[] args) throws InterruptedException, ExecutionException {ExecutorService executorService = Executors.newSingleThreadExecutor();Callable<String> stringCallable = () -> {Thread.sleep(1000);return "hello edpresso";};Future<String> stringFuture = executorService.submit(stringCallable);while(!stringFuture.isDone() && !stringFuture.isCancelled()) {Thread.sleep(200);System.out.println("Waiting for task completion...");}String result = stringFuture.get();System.out.println("Retrieved result from the task - " + result);executorService.shutdown();}}
Explanation
- Line 1: We import the relevant classes.
- Line 7: We define a single-threaded executor service.
- Lines 9 to 11: We define a callable that sleeps for one second and returns a string.
- Line 14: We get a future object as a result of submitting the callable to the executor service.
- Lines 16 to 19: We wait for the future to complete in a
whileloop. - Line 21: We get the result of the future using the
get()method. - Line 23: The result is printed to the console.
- Line 25: The executor service is shut down.