Future
in Java?The submit()
method submits a task to a thread for execution. It does not, however, know when the task’s outcome will be available. As a result, it returns a Future
, 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 Future
is similar to Promise
. It reflects the outcome of a calculation that will be completed at a later date.
Hence, a Future
is a placeholder used to store the result of an asynchronous computation.
get()
methodThe get
method waits for the given amount of time for the processing to complete and retrieves the result if available. The method throws a TimeoutException
if the wait time exceeds the given time.
V get(long timeout, TimeUnit unit)
long timeout
: This is the maximum amount of time to wait.TimeUnit unit
: This is the unit of time.This method returns the result of the computation.
import java.util.concurrent.*;public class Main {public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {ExecutorService executorService = Executors.newSingleThreadExecutor();Callable<String> stringCallable = () -> {Thread.sleep(1000);return "hello edpresso";};Future<String> stringFuture = executorService.submit(stringCallable);long timeOut = 2;TimeUnit timeUnit = TimeUnit.SECONDS;String result = stringFuture.get(timeOut, timeUnit);System.out.println("Retrieved result from the task - " + result);executorService.shutdown();}}
Future
object as a result of submitting the callable to executorService
.Future
using the get()
method passing the amount of time to wait and the unit of measurement of the wait time.executorService
is shut down.