Future

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Future<V> represents the result of an asynchronous computation.
  • When you submit a Callable to an ExecutorService, it instantly returns a Future object.
  • You can use the Future to check if the task is done, wait for its result, or cancel it.

Concept

When you order food at a busy restaurant, you don’t stand at the counter waiting. The cashier gives you a receipt with an order number (a Future). You can go sit down, chat with friends, and periodically look at the screen to see if your order number is ready (future.isDone()).
When you are ready to eat, you go to the counter and present the receipt (future.get()). If the food is ready, you get it instantly. If it’s not, you are forced to stand there and wait until it is (blocking).

Examples

import java.util.concurrent.*;

public class FutureExample {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        
        ExecutorService executor = Executors.newSingleThreadExecutor();
        
        // Submit a background task that takes 3 seconds
        Future<Integer> future = executor.submit(() -> {
            Thread.sleep(3000);
            return 42;
        });
        
        System.out.println("Main thread is not blocked!");
        
        // We can do other things while the background thread works...
        while (!future.isDone()) {
            System.out.println("Waiting for result...");
            Thread.sleep(1000);
        }
        
        // .get() will block if not done, but we already checked!
        Integer result = future.get(); 
        System.out.println("The answer is: " + result);
        
        executor.shutdown();
    }
}

Interview Questions

Q: What happens if the Callable throws an exception?
A: If the background task throws an exception (e.g., NullPointerException), the Future catches it and holds onto it. The worker thread does not crash the application. However, the moment you call future.get(), the Future will wrap the original exception inside an ExecutionException and throw it on the main thread.

Q: Can you cancel a Future?
A: Yes, by calling future.cancel(true).
If the task is waiting in the queue, it simply gets deleted and will never run.
If the task is already running, the true flag tells the Executor to send a Thread.interrupt() signal to the worker thread. If the worker thread’s code is designed to respect interrupts (e.g., it is in a Thread.sleep() or checking Thread.interrupted()), it will stop. If it’s in a tight CPU loop that ignores interrupts, cancel(true) won’t actually stop the execution, but future.get() will still throw a CancellationException.