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.
get()
methodThe get()
method is a blocking call. It is used to wait for the processing of the task to finish and retrieve the result.
V get()
The method has no parameters.
This method returns the result of the computation.
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();}}
while
loop.get()
method.