Card 03/ 09

ComparisonDifficulty: Intermediate1 min

Runnable Against Callable: What Each One Can Hand Back

Both are one-method interfaces describing a piece of work, and both can be written as a lambda. They differ in the two things a method can produce: a value, and an exception.

The two task interfaces
Compared onRunnableCallable<V>
The methodvoid run()V call() throws Exception
Returns a valueNoYes
May throw a checked exceptionNoYes
Submitting gives youFuture<?>, which is null when it completesFuture<V>, holding the result
Used byThread, execute, submitsubmit, invokeAll
java
Future<?> a = pool.submit(() -> log.info("done"));

Future<Long> b = pool.submit(() -> countRowsIn(file));

The compiler chooses between them from the lambda's body: line 1 produces nothing so it is a Runnable, and line 3 produces a long so it is a Callable. Nothing in the source says which.

The decision rule. If the task produces an answer somebody wants, or can fail in a way somebody should hear about, it is a Callable. Otherwise Runnable is fine — and the difference matters most for the exception, which brings the next card.