Java Reference ยท Concurrency
The Callable interface
Reference for java.util.concurrent.Callable: tasks that return a value and may throw checked exceptions, how it differs from Runnable, and how to submit it.
Callable<V> is a functional interface for a task that produces a result. It is the sibling of Runnable, with two differences: its method call() returns a value, and it is allowed to throw checked exceptions. Executors turn the returned value or the thrown exception into a Future.
Because both are functional interfaces, a lambda can fit either one. The compiler chooses by looking at the body: a lambda that returns a value (or throws) is a Callable, one that returns nothing is a Runnable.
Callable<Integer> job = () -> 6 * 7; Integer answer = job.call(); // call() declares "throws Exception"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
@FunctionalInterface public interface Callable<V> { V call() throws Exception; }
| Aspect | Callable<V> |
Runnable |
|---|---|---|
| Method | V call() throws Exception |
void run() |
| Returns a result | Yes | No |
| May throw checked exceptions | Yes | No |
| Since | Java 5 | Java 1.0 |
Usable with new Thread(...) |
No | Yes |
Accepted by submit, invokeAll, invokeAny |
Yes | submit only |
Throws: whatever call() throws. When run by an executor, it ends up as the cause of an ExecutionException from Future.get().
Usage notes
- A
Threadcannot run aCallabledirectly. Wrap it in aFutureTask, or use an executor. - Lambda ambiguity.
submit(() -> doWork())picksCallableifdoWork()returns a value, otherwiseRunnable. To force one, assign the lambda to a typed variable first or add a cast. - A
Callable<Void>must returnnull.() -> { work(); return null; }is the explicit way when you need aCallablewithout a result. call()can declare narrower exceptions or none, as theChunkrecord shows; callers holding aChunkreference then do not needthrows Exception.- Exceptions are delayed. Nothing is reported until
get()is called, so a fire-and-forgetCallablecan fail silently. - Task state belongs to the task. If several calls share mutable fields, protect them or make the task immutable (records work well).
Related
Future,ExecutorService,CompletableFuture,Thread- Lessons: Executors, Threads