VOOZH about

URL: https://www.geeksforgeeks.org/java/future-and-futuretask-in-java/

⇱ Future and FutureTask in java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Future and FutureTask in java

Last Updated : 11 Jul, 2025

Prerequisite: Future and callable

Future:

A Future interface provides methods to check if the computation is complete, to wait for its completion and to retrieve the results of the computation. The result is retrieved using Future's get() method when the computation has completed, and it blocks until it is completed. 
Future and FutureTask both are available in java.util.concurrent package from Java 1.5.

FutureTask:

  1. FutureTask is a concrete implementation of the Future, Runnable, and RunnableFuture interfaces and therefore can be submitted to an ExecutorService instance for execution.
  2. When calling ExecutorService.submit() on a Callable or Runnable instance, the ExecutorService returns a Future representing the task. and one can create it manually also.
  3. FutureTask acts similar to a CountDownLatch when calling get() in that it waits for the task to complete or error out.
  4. Behaviour of the parameterless get() method depends on the state of the task. If tasks are not completed, get() method blocks until the task is completed. Once the task complete, it returns the result or throws an ExecutionException.
  5. An overloaded variant of get() allows passing a timeout parameter to limit the amount of time the thread waits for a result.

Example:  When submitting a FutureTask instance to a thread pool (ExecutorService instance) , it returns a Future object immediately. This Future object can be used for task completion and getting result of computation asynchronously. 
 

👁 Image

Examples: Create two task. After one is completely executed, then after waiting 2000 millisecond, second task is being executed

Note: Online IDE does not work properly on sleep() method. 


Output
pool-1-thread-1
FutureTask1 output = FutureTask1 is complete
Waiting for FutureTask2 to complete
Exception: java.util.concurrent.TimeoutException
Waiting for FutureTask2 to complete
Exception: java.util.concurrent.TimeoutException
Waiting for FutureTask2 to complete
Exception: java.util.concurrent.TimeoutException
Waiting for FutureTask2 to complete
pool-1-thread-2
FutureTask2 output=FutureTask2 is complete
Both FutureTask Complete

Reference:  


 

Comment