skip to content

How does Supplier<T> differ from Callable<V> in Java, and when does the checked-exception difference decide which one you use?

level: middleimportance: should knowfreq 46%

answer

  1. same shape, one clause apart
  2. what the lambda body may throw
  3. who must catch at the call
  4. which parameter the API declares
  5. an adapter works in one direction

basics

~20 s

Both take no arguments and return a value, but Callable.call declares throws Exception and Supplier.get declares nothing. A lambda body throwing a checked Exception subclass compiles as Callable; as Supplier it must handle it itself. Often the API's parameter decides.

solid answer

~40 s

`Supplier<T>.get()` and `Callable<V>.call()` both take nothing and return a value, and the contract difference the compiler enforces is `call`'s `throws Exception`. Under JLS 11.2.3, a `Supplier` lambda whose body can throw a checked exception does not compile unless it handles it, typically by wrapping it in something like `UncheckedIOException`. The reverse cost falls on the caller: code invoking `call()` directly must catch or declare `Exception`. Usually the API decides for you: `CompletableFuture.supplyAsync`, `Optional.orElseGet` and `Stream.generate` declare `Supplier`, while `ExecutorService.submit` and `FutureTask` take `Callable`. When you design the parameter yourself, the exception does decide: choose `Callable` when a checked failure should reach the code running the task, as one surfacing from `Future.get()`, and `Supplier` for a value source whose callers should not need a `catch`.

code

java · 39 lines
java
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Supplier;

class SupplierVsCallable {
    public static void main(String[] args) throws InterruptedException {
        Path missing = Path.of("/no/such/file");

        // Supplier<String> rejected = () -> Files.readString(missing);  // unreported exception IOException
        Callable<String> task = () -> Files.readString(missing);
        Supplier<String> wrapped = () -> {
            try {
                return Files.readString(missing);
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        };

        try (ExecutorService pool = Executors.newSingleThreadExecutor()) {
            pool.submit(task).get();
        } catch (ExecutionException e) {
            System.out.println(e.getCause().getClass().getSimpleName()); // NoSuchFileException
        }

        try {
            CompletableFuture.supplyAsync(wrapped).join();
        } catch (CompletionException e) {
            System.out.println(e.getCause().getClass().getSimpleName()); // UncheckedIOException
        }
    }
}

go deeper

for a junior

Recall the two signatures: T get() and V call() throws Exception. A lambda that throws a checked Exception subclass compiles as a Callable but not as a Supplier unless it handles the exception itself.

for a middle

Explain the compile-time rule from JLS 11.2.3 and its other side, that calling call() forces a catch of Exception. Show the one-way adapter: supplier::get fits Callable, and callable::call does not fit Supplier.

for a senior

Show how failures travel: ExecutionException from Future.get, CompletionException from join, and the extra layer a wrapping Supplier adds. Unwrap causes deliberately when logging or retrying, and keep interruption handling out of a blanket catch of Exception.

for a principal

Weigh the parameter type of a shared API: Callable tells callers failure is normal but erases the checked type, and Supplier keeps call sites clean but pushes wrapping onto each lambda. A dedicated interface costs a type yet keeps the specific exception.

## Two declarations, one enforced difference Both are **functional interfaces**, interfaces with a single abstract method that a lambda can implement, and both take no arguments and return a value: | | `Supplier<T>` | `Callable<V>` | |---|---|---| | Package | `java.util.function` | `java.util.concurrent` | | Since | Java 1.8 | Java 1.5 | | Method | `T get()` | `V call() throws Exception` | | Javadoc's summary | "Represents a supplier of results" | "A task that returns a result and may throw an exception" | | JDK methods taking it | `Optional.orElseGet`, `Stream.generate`, `ThreadLocal.withInitial`, `CompletableFuture.supplyAsync` | `ExecutorService.submit`, `ExecutorService.invokeAll`, `ScheduledExecutorService.schedule`, the `FutureTask` constructor | Apart from being separate types, the `throws Exception` clause is the one contract difference the compiler enforces. The rest is convention. `Supplier`'s Javadoc adds that there is "no requirement that a new or distinct result be returned each time", and `Callable`'s says its instances are "potentially executed by another thread". Neither is a rule about threads: `supplyAsync` runs a `Supplier` on another thread, and `call()` can be invoked inline. Both can throw unchecked exceptions. ## What the checked exception changes at compile time A **checked exception** is one the compiler makes you catch or declare. JLS 11.2.3 makes it a compile-time error if a lambda body can throw a checked exception that the target's `throws` clause does not allow. With `Files.readString(path)`, which declares `IOException`: - `Supplier<String> s = () -> Files.readString(path);` fails with `unreported exception IOException; must be caught or declared to be thrown`. - `Callable<String> c = () -> Files.readString(path);` compiles. - `Callable<Object> c = () -> handle.invoke();`, on a `MethodHandle`, fails too, with `unreported exception Throwable`: `throws Exception` covers `Exception`'s subclasses, and `Throwable` is checked but sits above it (JLS 11.1.1). The cost then moves to whoever calls it, because `call()` itself declares `Exception`: - Code invoking `c.call()` directly must catch or declare `Exception`, and a `catch (Exception e)` also catches every runtime exception. - The `IOException` detail is gone from the signature: through a variable typed `Callable`, the compiler knows only `Exception`. - A class implementing `Callable` may narrow the clause, as in `public String call()` with no `throws`, and code holding that class type needs no `catch`. The narrowing is lost once the object is held as a `Callable`. Method references follow the same rule (JLS 15.13.2). `supplier::get` fits a `Callable`, because a method declaring no exception satisfies `throws Exception`. `callable::call` does not fit a `Supplier`: javac reports `incompatible thrown types Exception in functional expression`. So a `Supplier` adapts to a `Callable` with no extra code, and the reverse needs a `try`/`catch`. Overloading offers no way out. With `run(Supplier<String>)` and `run(Callable<String>)`, the call `run(() -> "x")` gives `reference to run is ambiguous`, and it stays ambiguous when the body throws `IOException`. The conditions for one function type being more specific (JLS 15.12.2.5) compare parameter and return types and do not mention `throws` clauses. An API offering both should use two method names, or each lambda call site needs a cast such as `(Callable<String>) () -> "x"`. ## Where a failure surfaces at run time - **`ExecutorService.submit(callable)`**: the exception is captured, and `Future.get()` throws `ExecutionException` with the original as its cause. - **`CompletableFuture.supplyAsync(supplier)`**, where the body wrapped `IOException` in `UncheckedIOException`: `join()` throws `CompletionException` and `get()` throws `ExecutionException`, each with the `UncheckedIOException` as its cause, so the `IOException` sits one level deeper. - **`supplier.get()` called directly**, as `Optional.orElseGet` does when no value is present: the unchecked exception propagates straight to the caller. ## When the exception decides Most of the time the API has already chosen, and you adapt to its parameter: - **The API takes `Supplier` and the body throws a checked exception**: catch it in the lambda and rethrow it unchecked, as with `UncheckedIOException` for `IOException`. - **The API takes `Callable` and you hold a `Supplier`**: pass `supplier::get`. Passing the variable itself, as in `executor.submit(supplier)`, does not compile, because the two types are unrelated. When you design the parameter yourself, ask who should handle the failure: - Choose **`Callable`** when failure is an expected outcome and your code has a place to deal with `Exception`, as a task runner does. - Choose **`Supplier`** when a value is expected back and a `catch` would be noise for callers, as with lazy defaults and factories. - Declare your own interface when callers need a specific checked type rather than `Exception`. When no checked exception is involved, the choice is convention: `Callable` signals a task to run, `Supplier` a source of values. `StructuredTaskScope.fork`, a preview API at both Java 25 and Java 27, takes a `Callable` or a `Runnable`, so a subtask with a checked failure fits it directly.

  • Can a Java Supplier variable be used where a Callable is expected, and the other way round?
    Not directly, since the types are unrelated. `supplier::get` fits a `Callable`, because a method declaring no exception satisfies `throws Exception`. `callable::call` does not fit a `Supplier`: javac reports `incompatible thrown types Exception in functional expression`, because JLS 15.13.2 requires the target's `throws` clause to allow each checked exception. That direction needs a lambda with `try`/`catch`.
  • If a Java method is overloaded on Supplier<String> and Callable<String>, can a checked exception in the lambda body pick the overload?
    No. `run(() -> "x")` gives `reference to run is ambiguous`, and so does a body that throws `IOException`. The conditions in JLS 15.12.2.5 for one function type being more specific compare parameter and return types and do not mention `throws` clauses. Such methods need different names, or a cast at each lambda call site.
  • Where does a task's failure surface with a Callable through ExecutorService.submit, compared with a wrapping Supplier through CompletableFuture.supplyAsync?
    With `submit`, `Future.get()` throws `ExecutionException` whose cause is the original exception. With `supplyAsync`, `join()` throws `CompletionException` and `get()` throws `ExecutionException`, and the cause is your `UncheckedIOException`, with the `IOException` inside it. In both, the task's failure appears when you ask for the result, not when you submit the task.

  • Supplier.get can never throw an exception, so code calling it needs no failure handling.
  • Supplier is for synchronous code and Callable is for asynchronous code.
  • A Supplier variable can be passed straight to ExecutorService.submit because the shapes match.
  • Overload resolution picks the Callable overload when the lambda body throws a checked exception.
  • Callable.call always runs on another thread, so calling it inline is not allowed.
  • A Callable variable's callers need to catch only the IOException its lambda body throws.

java.util.function.Supplier
Java 1.8
java.util.concurrent.Callable
Java 1.5
java.util.concurrent.CompletableFuture
Java 1.8
java.util.concurrent.ExecutorService
Java 1.5
java.util.concurrent.Future
Java 1.5

Assumes Java 27; Callable dates from Java 5 and Supplier from Java 8, the rules shown are the same at Java 25, and StructuredTaskScope is a preview API at both.

context