Callable Interface in Java: Return Results from Tasks
The Callable interface in Java represents a task that returns a result and may throw an exception. It lives in the java.util.concurrent package and is the usual way to hand value-producing work to an executor.
This tutorial shows how to write a Callable as a class or a lambda, how to run it, how to read its result through a Future, and how its checked exceptions reach the caller.
1. What Is the Callable Interface?
Callable<V> is a generic, functional interface with a single method, V call() throws Exception. The type parameter V is the type of the result. Because it has only one abstract method, you can implement it with a lambda or a method reference.
It was added in Java 5 together with the Executor Framework. Its sibling, Runnable, describes work that returns nothing; Callable fills the gap when the caller needs an answer back. For a side-by-side comparison, see Runnable vs Callable.
2. Syntax
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}
You can implement it in two common ways:
// 1. As a named class
class PriceCheck implements Callable<Integer> {
@Override
public Integer call() {
return 499;
}
}
// 2. As a lambda that returns a value
Callable<Integer> priceCheck = () -> 499;
A lambda becomes a Callable only when its body returns a value. A lambda with no return value matches Runnable instead, which matters when you pass it to an overloaded method such as submit().
3. Example: Calculating Shipping Costs in Parallel
A logistics service prices three parcels at the same time. Each price comes from a slow rate service, so each calculation runs as a separate Callable.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ShippingCostCalculator {
record Parcel(String id, double weightKg, int distanceKm) {}
// A named Callable: computes the shipping cost of one parcel
static class CostTask implements Callable<Double> {
private final Parcel parcel;
CostTask(Parcel parcel) {
this.parcel = parcel;
}
@Override
public Double call() throws InterruptedException {
Thread.sleep(100); // simulate a rate-service call
return 4.50 + parcel.weightKg() * 0.80 + parcel.distanceKm() * 0.02;
}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
List<Parcel> parcels = List.of(
new Parcel("PX-101", 2.0, 120),
new Parcel("PX-102", 7.5, 40),
new Parcel("PX-103", 0.5, 610));
try (ExecutorService executor = Executors.newFixedThreadPool(3)) {
List<Future<Double>> costs = new ArrayList<>();
for (Parcel parcel : parcels) {
costs.add(executor.submit(new CostTask(parcel)));
}
// A lambda is also a Callable because it returns a value
Future<String> currency = executor.submit(() -> "EUR");
double total = 0;
for (int i = 0; i < parcels.size(); i++) {
double cost = costs.get(i).get();
total += cost;
System.out.printf("%s: %6.2f %s%n", parcels.get(i).id(), cost, currency.get());
}
System.out.printf("Total : %6.2f %s%n", total, currency.get());
}
}
}
PX-101: 8.50 EUR PX-102: 11.30 EUR PX-103: 17.10 EUR Total : 36.90 EUR
How the code works
CostTaskimplementsCallable<Double>, so itscall()method returns the price as aDouble.executor.submit(...)starts each task and immediately returns aFuture<Double>, a handle to the result that is not ready yet.- The lambda
() -> "EUR"is also a Callable, because it returns a value. get()waits until the matching task has finished, then returns its result. The loop reads the futures in submission order, so the output order is fixed.- The try-with-resources block calls
close(), which waits for all tasks and shuts the executor down (available since Java 19).
4. Example: Reporting a Checked Exception
call() is declared to throw Exception, so a Callable can signal failure with a checked exception. The executor captures it and hands it to whoever calls get().
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CarrierRateLookup {
// A checked exception: Runnable.run() could not throw this, Callable.call() can
static class RateUnavailableException extends Exception {
private static final long serialVersionUID = 1L;
RateUnavailableException(String message) {
super(message);
}
}
static final Map<String, Double> RATES = Map.of("NordFreight", 1.35, "SwiftCargo", 1.10);
static Callable<Double> rateFor(String carrier) {
return () -> {
Double rate = RATES.get(carrier);
if (rate == null) {
throw new RateUnavailableException("no tariff published for " + carrier);
}
return rate;
};
}
public static void main(String[] args) throws InterruptedException {
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
for (String carrier : new String[] {"NordFreight", "BlueLine", "SwiftCargo"}) {
Future<Double> rate = executor.submit(rateFor(carrier));
try {
System.out.println(carrier + " rate per km: " + rate.get());
} catch (ExecutionException e) {
Throwable cause = e.getCause();
System.out.println(carrier + " failed: " + cause.getClass().getSimpleName()
+ " (" + cause.getMessage() + ")");
}
}
}
}
}
NordFreight rate per km: 1.35 BlueLine failed: RateUnavailableException (no tariff published for BlueLine) SwiftCargo rate per km: 1.1
How the code works
RateUnavailableExceptionextendsException, so it is checked. ARunnablecould not throw it without wrapping it.- For the unknown carrier,
call()throws. The executor stores the exception inside theFutureinstead of printing it. get()rethrows it wrapped inExecutionException, andgetCause()returns the original exception.- The other carriers are not affected; each task succeeds or fails on its own.
5. Ways to Run a Callable
| API | What it does |
|---|---|
ExecutorService.submit(Callable) | Runs one task and returns a Future. |
invokeAll(tasks) | Runs a batch and waits for all of them. |
invokeAny(tasks) | Returns the result of the first task that succeeds. |
new FutureTask<>(callable) | Wraps it as a Runnable, so even a plain Thread can run it. |
Executors.callable(runnable, result) | Converts an existing Runnable into a Callable. |
A Thread cannot run a Callable directly, because its constructor accepts only a Runnable. Use an executor, or wrap the task in a FutureTask.
6. Important Characteristics
- Generic: the result type is fixed at compile time, so
get()needs no cast. - Functional: annotated with
@FunctionalInterface, so lambdas and method references work. - Exception-friendly:
call()can throw any exception, checked or unchecked. - Stateless by contract: the interface says nothing about threads; the executor decides where and when the task runs.
7. Common Mistakes and Best Practices
- Calling
get()too early. It blocks. Submit all tasks first, then collect results. - Ignoring
ExecutionException. Always inspectgetCause(); that is where the real error is. - Waiting forever. Prefer
get(timeout, unit)when a task depends on a slow or unreliable service. - Sharing mutable state. Return results from
call()instead of writing to shared fields from several tasks. - Swallowing interrupts. If
call()catchesInterruptedException, restore the flag withThread.currentThread().interrupt()or rethrow it.
8. Summary
Callable<V>is a functional interface whosecall()method returns a value of typeV.- Unlike
Runnable, it can throw checked exceptions. - Submit it to an
ExecutorServiceand read the result through aFuture. - Failures arrive as
ExecutionException; the original exception is its cause.
Related Tutorials
9. References
Frequently Asked Questions (FAQ)
Q1. Is Callable a functional interface?
Yes. Callable is annotated with @FunctionalInterface and has one abstract method, call(), so you can create it with a lambda such as () -> 42 or with a method reference.
Q2. Can a Callable return null?
Yes. call() returns a value of type V, and null is a valid reference value. Use Callable<Void> and return null when you need the Callable signature but no real result.
Q3. Can I pass a Callable to the Thread constructor?
No. Thread accepts only a Runnable. Wrap the Callable in a FutureTask, which implements Runnable, or submit it to an ExecutorService.
Q4. How do I convert a Runnable into a Callable?
Use Executors.callable(runnable), which returns a Callable<Object> that yields null, or Executors.callable(runnable, result) to return a fixed result of your choice.
Q5. What happens when call() throws an exception?
The executor catches it and stores it in the task's Future. Calling get() then throws ExecutionException, and getCause() returns the exception that call() threw.