Video in progress

What is a Future, and what should you watch out for when working with its get() method?

A Future is a "ticket" for the result of a computation that hasn't finished yet. get() blocks the current thread until the result is ready, so it is usually called with a timeout.

📖 Answer

Future<Report> future = executor.submit(() -> buildReport(month));

// ... other work

try {
    Report r = future.get(5, TimeUnit.SECONDS);
} catch (TimeoutException e) {
    future.cancel(true);   // sends an interrupt to the running thread
} catch (ExecutionException e) {
    log.error("hisobot yiqildi", e.getCause());
}

What to watch out for:

  • get() without a timeout: if an external service hangs, your thread hangs forever too;
  • an exception in the task only shows up when get() is called. If nobody calls get(), the error quietly disappears;
  • cancel(true) doesn't forcibly kill the thread; it only sets the interrupt flag. If the task doesn't check it, it keeps running.

The drawback of Future is that you can't chain "then do this" onto the result. That is what CompletableFuture is for.