Skip to content
Tutorials Center
My learning

Topics

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.

Java
Callable<Integer> job = () -> 6 * 7;
Integer answer = job.call();   // call() declares "throws Exception"

Try it

Java Callable vs Runnable

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.

Java Collecting results from many callables

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

Java
@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 Thread cannot run a Callable directly. Wrap it in a FutureTask, or use an executor.
  • Lambda ambiguity. submit(() -> doWork()) picks Callable if doWork() returns a value, otherwise Runnable. To force one, assign the lambda to a typed variable first or add a cast.
  • A Callable<Void> must return null. () -> { work(); return null; } is the explicit way when you need a Callable without a result.
  • call() can declare narrower exceptions or none, as the Chunk record shows; callers holding a Chunk reference then do not need throws Exception.
  • Exceptions are delayed. Nothing is reported until get() is called, so a fire-and-forget Callable can fail silently.
  • Task state belongs to the task. If several calls share mutable fields, protect them or make the task immutable (records work well).