Why this matters
- Most real tasks produce a result or fail, and
Runnablecan express neither — it cannot return a value and cannot throw a checked exception. - A
Futurethat silently holds an exception nobody ever callsget()on is a genuinely common way to lose an error. - Understanding why
Futureis limited is what makesCompletableFuturefeel 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
Callable
Loading compiler…
| Aspect | Runnable | Callable |
|---|---|---|
| Method | void run() | V call() throws Exception |
| Returns a value | No | Yes |
| Checked exceptions | Cannot throw any | May throw anything |
| Added in | Java 1.0 | Java 5 |
| Submit with | execute() or submit() | submit() |
Method
Runnablevoid run()CallableV call() throws ExceptionReturns a value
RunnableNoCallableYesChecked exceptions
RunnableCannot throw anyCallableMay throw anythingAdded in
RunnableJava 1.0CallableJava 5Submit 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.
Loading compiler…
The five methods
get()— blocks until the task completes, then returns the value.get(timeout, unit)— the same, but throwsTimeoutExceptionon 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
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.