Skip to main content
PreparationZone Logo
PrepZone

Callable, Future and Fork/Join

Returning values from tasks, where Future falls short, and how fork/join splits big work.

Pass checkpoint below

Read these first

Why this matters

  • Most real tasks produce a result or fail, and Runnable can express neither — it cannot return a value and cannot throw a checked exception.
  • A Future that silently holds an exception nobody ever calls get() on is a genuinely common way to lose an error.
  • Understanding why Future is limited is what makes CompletableFuture feel like a solution rather than extra API.
supplyAsync — fetch user
supplyAsync — fetch orders
Build the responseRuns when both finish
Fallback valueFailure handled in the chain
Each stage declares what happens next instead of blocking for a result. Independent calls run in parallel and only join where you actually combine them.

Callable

Java
Loading compiler…
AspectRunnableCallable
Methodvoid run()V call() throws Exception
Returns a valueNoYes
Checked exceptionsCannot throw anyMay throw anything
Added inJava 1.0Java 5
Submit withexecute() or submit()submit()
  • Method

    Runnablevoid run()
    CallableV call() throws Exception
  • Returns a value

    RunnableNo
    CallableYes
  • Checked exceptions

    RunnableCannot throw any
    CallableMay throw anything
  • Added in

    RunnableJava 1.0
    CallableJava 5
  • Submit with

    Runnableexecute() or submit()
    Callablesubmit()

Callable is the one to reach for whenever a task produces a result or can fail meaningfully.

Future

Submitting a Callable returns a handle to a result that does not exist yet.

Java
Loading compiler…

The five methods

  • get() — blocks until the task completes, then returns the value.
  • get(timeout, unit) — the same, but throws TimeoutException on expiry. Prefer this form.
  • isDone() — true once finished, whether by success, exception or cancellation.
  • cancel(mayInterruptIfRunning) — prevents a queued task from starting; interrupts a running one if the flag is true and the task cooperates.
  • isCancelled() — true if cancellation succeeded.

Exceptions arrive wrapped

Java
Loading compiler…

Anything the task throws is wrapped in ExecutionException. Always unwrap with getCause() before logging, or the message says nothing useful.

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 5 sections

  • Why Future is limited
  • invokeAll and invokeAny
  • ScheduledExecutorService
  • Fork/Join
  • Common misreadings

Test yourself

Answer these before moving on — recall is what makes it stick.