0Pricing
Java Academy · Lesson

Future and Error Handling

Use Future.get with timeouts, handle ExecutionException, and cancel running tasks.

Future and Error Handling is a free Java Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What is Future?

A Future<V> represents the pending result of an async computation. It provides methods to check completion, wait for result, and handle errors.

import java.util.concurrent.*;

ExecutorService pool = Executors.newFixedThreadPool(2);
Future<Integer> future = pool.submit(() -> {
    Thread.sleep(1000);
    return 42;
});

System.out.println("Is done? " + future.isDone()); // false
Integer result = future.get(); // blocks
System.out.println("Result: " + result); // 42
pool.shutdown();

future.get() with Timeout

Always prefer the timeout variant to prevent hanging indefinitely:

try {
    Integer result = future.get(5, TimeUnit.SECONDS);
    System.out.println(result);
} catch (TimeoutException e) {
    System.out.println("Timed out");
    future.cancel(true); // interrupt the task
} catch (InterruptedException e) {
    Thread.currentThread().interrupt();
} catch (ExecutionException e) {
    System.out.println("Task threw: " + e.getCause());
}

ExecutionException

If the task threw an exception, future.get() wraps it in ExecutionException. Unwrap with getCause():

Future<String> failing = pool.submit(() -> {
    throw new IllegalArgumentException("bad input");
});

try {
    failing.get();
} catch (ExecutionException e) {
    Throwable cause = e.getCause();
    System.out.println(cause.getClass().getSimpleName()); // IllegalArgumentException
    System.out.println(cause.getMessage()); // bad input
}

Cancelling a Future

cancel(mayInterruptIfRunning) attempts to cancel the task. Returns true if successful. If mayInterruptIfRunning is true, an interrupt is sent to the running thread.

Future<String> f = pool.submit(() -> {
    try {
        Thread.sleep(10_000); // long task
        return "done";
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return "interrupted";
    }
});

boolean cancelled = f.cancel(true); // send interrupt
System.out.println("Cancelled: " + cancelled); // true
System.out.println("Is cancelled: " + f.isCancelled()); // true

isCancelled vs isDone

isDone() returns true if the task completed normally, threw an exception, or was cancelled. isCancelled() returns true only if it was cancelled.

// After cancel:
System.out.println(f.isDone());       // true
System.out.println(f.isCancelled()); // true

// After normal completion:
Future<Integer> done = pool.submit(() -> 5);
done.get(); // wait
System.out.println(done.isDone());       // true
System.out.println(done.isCancelled()); // false

CompletionService for First-Available Results

ExecutorCompletionService wraps a pool and provides a take() method to retrieve the next completed Future (in completion order, not submission order):

ExecutorCompletionService<Integer> cs =
    new ExecutorCompletionService<>(pool);

for (int i = 0; i < 5; i++) {
    final int delay = 5 - i; // submit fastest last
    cs.submit(() -> { Thread.sleep(delay * 100); return delay; });
}

for (int i = 0; i < 5; i++) {
    Future<Integer> f = cs.take(); // next completed
    System.out.println(f.get());
}

Handling Multiple Futures Safely

When collecting results from many futures, iterate and handle exceptions per-future:

List<Future<String>> futures = new ArrayList<>();
for (int i = 0; i < 5; i++) {
    final int id = i;
    futures.add(pool.submit(() ->
        id % 2 == 0 ? "ok_" + id : (() -> { throw new RuntimeException("fail_"+id); }).get()
    ));
}

for (Future<String> f : futures) {
    try {
        System.out.println(f.get());
    } catch (ExecutionException e) {
        System.out.println("Error: " + e.getCause().getMessage());
    }
}

Future.get() After Pool Shutdown

Submitting after shutdown() throws RejectedExecutionException. But Futures submitted BEFORE shutdown can still be retrieved after shutdown:

ExecutorService pool2 = Executors.newFixedThreadPool(2);
Future<Integer> f = pool2.submit(() -> 99);
pool2.shutdown(); // no new tasks

// Still valid — task was submitted before shutdown:
System.out.println(f.get()); // 99

try {
    pool2.submit(() -> 0); // throws!
} catch (RejectedExecutionException e) {
    System.out.println("Pool shut down");
}

FutureTask: Manual Future

FutureTask<V> implements both Runnable and Future<V> — useful when you need a Future without an ExecutorService:

FutureTask<String> task = new FutureTask<>(() -> "computed");
new Thread(task).start(); // run in any thread
System.out.println(task.get()); // computed

Retry Pattern with Future

Implement simple retry logic around future.get():

Future<String> future = pool.submit(() -> {
    if (Math.random() < 0.7) throw new RuntimeException("transient error");
    return "success";
});

for (int attempt = 0; attempt < 3; attempt++) {
    try {
        System.out.println(future.get());
        break;
    } catch (ExecutionException e) {
        System.out.println("Attempt " + (attempt+1) + " failed");
        if (attempt == 2) throw e;
        future = pool.submit(() -> "retry"); // resubmit
    }
}

Limitations of Future

java.util.concurrent.Future has limitations:

  • No callbacks — must block with get()
  • Cannot chain transformations
  • Cannot combine multiple futures

Use CompletableFuture (next course) for reactive, non-blocking composition.

Quick Check

A task throws an exception. When you call future.get(), what exception is thrown?

Recap: Future and Error Handling

Key takeaways:

  • future.get() blocks; always use timeout variant
  • ExecutionException wraps task exceptions; unwrap with getCause()
  • cancel(true) sends interrupt; isDone/isCancelled for status
  • ExecutorCompletionService.take() retrieves futures in completion order
  • FutureTask implements both Runnable and Future

Frequently asked questions

Is the “Future and Error Handling” lesson free?

Yes — the full text of “Future and Error Handling” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Future and Error Handling”?

Use Future.get with timeouts, handle ExecutionException, and cancel running tasks. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Future and Error Handling” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. ExecutorService and Thread Pool Types
  2. Submitting Tasks: Runnable vs Callable
  3. Future and Error Handling
  4. ScheduledExecutorService for Recurring Tasks
← Back to Java Academy