Callable
Callable<V> is a task that returns a value or throws an exception. ExecutorService.submit runs it and gives you a Future<V>. It is Runnable with a result.
Detailed Explanation
Runnable.run is void and cannot throw checked exceptions. That is enough for "fire this side effect". It is not enough for "parse this file and give me the list". Callable.call returns V and may throw Exception. The executor catches the throw and stores it on the Future. future.get() rethrows it wrapped in ExecutionException.
You obtain a Callable as a lambda (() -> files.size()), a method reference, or a class. Executors.callable(runnable, result) adapts a Runnable. Generic V is the result type; use Callable<Void> and return null when you need checked exceptions but no value.
submit(Callable) returns Future. invokeAll runs a collection and waits. invokeAny returns the first successful result and cancels the rest. Those methods exist because a callable has a result to collect.
You reach for Callable whenever a pool should compute something you will read. You keep Runnable for side effects with no result (log::flush). You use CompletableFuture.supplyAsync when you want a composable future instead of the older Future.
The cost of ignoring Future.get() is a lost exception: the task failed and nobody noticed. The cost of calling get() on the executor thread that is supposed to run the task is a deadlock if the pool is saturated. The cost of a callable that mutates shared state without synchronization is a race, the same as Runnable.
call is invoked by a worker thread, not by submit. ThreadLocals, security context, and class loaders may differ from the submitting thread. Capture what you need in the callable's constructor or lambda.
Code Examples
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class LengthTask {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newSingleThreadExecutor();
Callable<Integer> task = () -> "Java".length();
Future<Integer> future = pool.submit(task);
System.out.println(future.get()); // prints: 4
pool.shutdown();
}
}import java.util.concurrent.Callable;
public class Failing {
static Callable<Integer> parse(String raw) {
return () -> Integer.parseInt(raw); // may throw NumberFormatException
}
public static void main(String[] args) {
try {
parse("x").call();
} catch (Exception e) {
System.out.println(e.getClass().getSimpleName()); // prints: NumberFormatException
}
}
}Common Gotchas
Exceptions live on the `Future`
if you never `get()`, they disappear into a worker thread.
`get()` on a saturated pool from a worker can deadlock
use a bigger pool, `invokeAll`, or `CompletableFuture`.
`Callable` is not a `@FunctionalInterface` in name only
it is one; lambdas work.
`call` runs on the worker
do not assume `Thread.currentThread()` is the submitter.