Card 03/ 09
All 9 cards
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.
| Compared on | Runnable | Callable<V> |
|---|---|---|
| The method | void run() | V call() throws Exception |
| Returns a value | No | Yes |
| May throw a checked exception | No | Yes |
| Submitting gives you | Future<?>, which is null when it completes | Future<V>, holding the result |
| Used by | Thread, execute, submit | submit, invokeAll |
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.