Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
future
timeout

How to get the result of a Future with timeout in Java

abhilash

What is the 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.

The get() method

The 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.

Syntax


V get(long timeout, TimeUnit unit)

Parameters

  • long timeout: This is the maximum amount of time to wait.
  • TimeUnit unit: This is the unit of time.

Return value

This method returns the result of the computation.

Example

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();
    }
}
Implementation of the get() method

Explanation

  • Line 1: We import the relevant classes.
  • Line 7: We define a single-threaded executor service.
  • Lines 9–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 executorService.
  • Line 16: The maximum amount of time to wait is defined.
  • Line 18: The unit for the time to wait is defined.
  • Line 20: We get the result of the Future using the get() method passing the amount of time to wait and the unit of measurement of the wait time.
  • Line 22: The result is printed to the console.
  • Line 24: executorService is shut down.

RELATED TAGS

java
communitycreator
future
timeout
RELATED COURSES

View all Courses

Keep Exploring