00:00

Callable Interface in Java: Return Results from Tasks

Last updated:

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

Callable.java (JDK declaration)
@FunctionalInterface
public interface Callable<V> {
    V call() throws Exception;
}

You can implement it in two common ways:

Usage.java
// 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.

ShippingCostCalculator.java
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());
        }
    }
}
Output
PX-101:   8.50 EUR
PX-102:  11.30 EUR
PX-103:  17.10 EUR
Total :  36.90 EUR

How the code works

  1. CostTask implements Callable<Double>, so its call() method returns the price as a Double.
  2. executor.submit(...) starts each task and immediately returns a Future<Double>, a handle to the result that is not ready yet.
  3. The lambda () -> "EUR" is also a Callable, because it returns a value.
  4. 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.
  5. 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().

CarrierRateLookup.java
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() + ")");
                }
            }
        }
    }
}
Output
NordFreight rate per km: 1.35
BlueLine failed: RateUnavailableException (no tariff published for BlueLine)
SwiftCargo rate per km: 1.1

How the code works

  1. RateUnavailableException extends Exception, so it is checked. A Runnable could not throw it without wrapping it.
  2. For the unknown carrier, call() throws. The executor stores the exception inside the Future instead of printing it.
  3. get() rethrows it wrapped in ExecutionException, and getCause() returns the original exception.
  4. The other carriers are not affected; each task succeeds or fails on its own.

5. Ways to Run a Callable

APIWhat 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 inspect getCause(); 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() catches InterruptedException, restore the flag with Thread.currentThread().interrupt() or rethrow it.

8. Summary

  • Callable<V> is a functional interface whose call() method returns a value of type V.
  • Unlike Runnable, it can throw checked exceptions.
  • Submit it to an ExecutorService and read the result through a Future.
  • Failures arrive as ExecutionException; the original exception is its cause.

Related Tutorials

9. References