Java Callable Interface
The Java Callable interface describes a task that returns a result and is allowed to throw a checked exception. It is the answer to a limitation of Runnable, whose run() method returns nothing and cannot throw checked exceptions.
You normally give a Callable to an ExecutorService, which runs it on a pool thread and hands you a Future. Later you call future.get() to collect the value. Callable is in the java.util.concurrent package and has been part of Java since version 5.
Callable vs Runnable in Java
Both interfaces represent a piece of work for a thread, and both are functional interfaces, so you can write them as lambdas. The differences are in what the method can return and throw.
Runnable | Callable<V> | |
|---|---|---|
| Package | java.lang | java.util.concurrent |
| Method | void run() | V call() throws Exception |
| Returns a value | No | Yes, of type V |
| Can throw checked exceptions | No | Yes |
Can be passed to new Thread(...) | Yes | No (wrap it in a FutureTask) |
Used with ExecutorService | execute() or submit() | submit(), invokeAll(), invokeAny() |
The full definition of the interface is just one method:
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}
The type parameter V is the type of the result. A Callable<Integer> returns an Integer, and a Callable<String> returns a String.
How to Create a Callable in Java
Callable as a Lambda
Because Callable has a single abstract method, a lambda that returns a value is enough. You can even call call() directly, although that runs the code in the current thread.
import java.util.concurrent.Callable;
public class FirstCallable {
public static void main(String[] args) throws Exception {
Callable<String> greeting = () -> "Hello from a Callable";
String message = greeting.call(); // runs right here, in the main thread
System.out.println(message + " (thread: " + Thread.currentThread().getName() + ")");
}
}
Output:
Hello from a Callable (thread: main)
How it works:
- The lambda
() -> "Hello from a Callable"takes no arguments and returns aString, so it matchesCallable<String>. greeting.call()simply runs the method. No new thread is involved.maindeclaresthrows Exceptionbecausecall()is allowed to throw any exception.
Callable as a Class
For larger tasks, write a class that implements Callable<V>. Fields hold the input, and call() returns the output.
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class PrimeCounterDemo {
// Counts the prime numbers between from and to (inclusive)
static class PrimeCounter implements Callable<Integer> {
private final int from;
private final int to;
PrimeCounter(int from, int to) {
this.from = from;
this.to = to;
}
@Override
public Integer call() {
int count = 0;
for (int n = Math.max(from, 2); n <= to; n++) {
if (isPrime(n)) count++;
}
return count;
}
private static boolean isPrime(int n) {
for (int divisor = 2; (long) divisor * divisor <= n; divisor++) {
if (n % divisor == 0) return false;
}
return true;
}
}
public static void main(String[] args) throws Exception {
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
Future<Integer> primes = executor.submit(new PrimeCounter(1, 100_000));
System.out.println("Task submitted, main thread is free...");
System.out.println("Primes up to 100,000: " + primes.get()); // waits for the result
}
}
}
Output:
Task submitted, main thread is free...
Primes up to 100,000: 9592
How it works:
PrimeCounterimplementsCallable<Integer>, socall()must return anInteger. Theintcount is auto-boxed.submit()starts the task on the pool thread and immediately returns aFuture<Integer>.mainkeeps running and prints its message.primes.get()blocks untilcall()has finished, then returns its value.call()here throws nothing, so thethrows Exceptionclause can be left out of the override.
Running a Callable with ExecutorService and Future
The real power of Callable appears when several run in parallel. Each submit() returns a Future, and you collect the results afterwards. This example splits the prime count across four workers.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ParallelPrimes {
static Callable<Integer> countPrimes(int from, int to) {
return () -> {
int count = 0;
for (int n = Math.max(from, 2); n <= to; n++) {
boolean prime = true;
for (int d = 2; (long) d * d <= n; d++) {
if (n % d == 0) { prime = false; break; }
}
if (prime) count++;
}
return count;
};
}
public static void main(String[] args) throws Exception {
int chunkSize = 50_000;
List<Future<Integer>> parts = new ArrayList<>();
try (ExecutorService executor = Executors.newFixedThreadPool(4)) {
for (int start = 1; start <= 200_000; start += chunkSize) {
parts.add(executor.submit(countPrimes(start, start + chunkSize - 1)));
}
int total = 0;
for (int i = 0; i < parts.size(); i++) {
int count = parts.get(i).get(); // wait for each chunk in turn
System.out.println("chunk " + (i + 1) + ": " + count + " primes");
total += count;
}
System.out.println("total primes up to 200,000: " + total);
}
}
}
Output:
chunk 1: 5133 primes
chunk 2: 4459 primes
chunk 3: 4256 primes
chunk 4: 4136 primes
total primes up to 200,000: 17984
How it works:
- The loop creates four
Callables for the ranges 1–50,000, 50,001–100,000, and so on, and submits them all before waiting for anything. - The four workers count their chunks at the same time.
- The second loop calls
get()on eachFuturein order. If a chunk is still running,get()waits; if it is already done,get()returns immediately.
Throwing Checked Exceptions from a Callable
call() is declared throws Exception, so a Callable can use methods like Files.readString() without wrapping them in try/catch. If the task throws, the exception is stored in the Future, and get() throws an ExecutionException whose cause is the original exception.
import java.nio.file.Files;
import java.nio.file.Path;
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 CallableException {
public static void main(String[] args) throws InterruptedException {
// Files.readString throws IOException, a checked exception
Callable<String> loadConfig = () -> Files.readString(Path.of("missing-config.json"));
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
Future<String> config = executor.submit(loadConfig);
try {
System.out.println("Config: " + config.get());
} catch (ExecutionException e) {
Throwable cause = e.getCause(); // the exception thrown by call()
System.out.println("Loading failed: " + cause);
System.out.println("Was it an IOException? " + (cause instanceof java.io.IOException));
}
}
}
}
Output:
Loading failed: java.nio.file.NoSuchFileException: missing-config.json
Was it an IOException? true
How it works:
- A
Runnablelambda could not callFiles.readString()without a try/catch, becauserun()cannot throw checked exceptions. ACallablecan. - The file does not exist, so
call()throwsNoSuchFileException, which is a subclass ofIOException. get()wraps it in anExecutionException.getCause()gives you back the real exception so you can handle it.
Note:
Future.get()can throw two checked exceptions:ExecutionExceptionwhen the task failed, andInterruptedExceptionwhen the waiting thread itself is interrupted. Handle or declare both.
Future get() with a Timeout and cancel()
A plain get() may wait forever if a task hangs. get(timeout, unit) waits only for a limited time and throws a TimeoutException if the result is not ready. You can then stop the task with cancel(true), which interrupts its thread.
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class CallableTimeout {
public static void main(String[] args) throws InterruptedException, ExecutionException {
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
Future<String> slowReport = executor.submit(() -> {
Thread.sleep(3000); // a report that takes 3 seconds
return "Annual sales report";
});
try {
String report = slowReport.get(500, TimeUnit.MILLISECONDS);
System.out.println("Got: " + report);
} catch (TimeoutException e) {
System.out.println("Report not ready after 500 ms");
boolean cancelled = slowReport.cancel(true); // interrupt the running task
System.out.println("cancelled : " + cancelled);
System.out.println("isCancelled: " + slowReport.isCancelled());
System.out.println("isDone : " + slowReport.isDone());
System.out.println("state : " + slowReport.state()); // Java 19+
}
}
}
}
Output:
Report not ready after 500 ms
cancelled : true
isCancelled: true
isDone : true
state : CANCELLED
How it works:
get(500, TimeUnit.MILLISECONDS)gives up after half a second and throwsTimeoutException. The task keeps running until it is cancelled.cancel(true)interrupts the worker thread, soThread.sleep()inside the task ends with anInterruptedException.- A cancelled
Futurecounts as done. Callingget()on it would throw aCancellationException.
| Future method | Purpose |
|---|---|
get() | Wait for the result |
get(timeout, unit) | Wait at most this long |
isDone() | true if finished, failed or cancelled |
cancel(mayInterrupt) | Try to stop the task |
isCancelled() | true if cancelled before it completed |
state() (Java 19+) | RUNNING, SUCCESS, FAILED or CANCELLED |
resultNow() (Java 19+) | The result of a successfully completed task, without waiting |
Running a Callable Without an Executor: FutureTask
new Thread() only accepts a Runnable. FutureTask bridges the gap: it implements both Runnable and Future, so you can pass it to a thread and later read the Callable's result from it.
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class FutureTaskDemo {
public static void main(String[] args) throws Exception {
Callable<Long> factorialOf20 = () -> {
long result = 1;
for (int i = 2; i <= 20; i++) result *= i;
return result;
};
FutureTask<Long> task = new FutureTask<>(factorialOf20);
Thread worker = new Thread(task, "factorial-worker"); // FutureTask is a Runnable
worker.start();
System.out.println("20! = " + task.get()); // FutureTask is also a Future
}
}
Output:
20! = 2432902008176640000
How it works:
FutureTaskwraps theCallable. Itsrun()method callscall()and stores the result.- The thread runs the
FutureTasklike any otherRunnable. task.get()waits for the thread to finish and returns the storedLong. 20! is the largest factorial that fits in along.
You can also convert in the other direction: Executors.callable(runnable, result) turns a Runnable into a Callable that returns the given result when it finishes.
Running Many Callables with invokeAll
ExecutorService.invokeAll() takes a collection of Callables, runs them, and returns their Futures in the same order. The version with a timeout cancels any task that has not finished in time, as described in Java ExecutorService.
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class InvokeAllCallables {
public static void main(String[] args) throws Exception {
List<Callable<Integer>> wordCounts = List.of(
() -> "Java threads run tasks".split(" ").length,
() -> "Callable returns a value".split(" ").length,
() -> "Future holds the result until you ask".split(" ").length);
try (ExecutorService executor = Executors.newFixedThreadPool(3)) {
List<Future<Integer>> results = executor.invokeAll(wordCounts);
int totalWords = 0;
for (Future<Integer> result : results) {
totalWords += result.get();
}
System.out.println("words per sentence: "
+ results.stream().map(Future::resultNow).toList());
System.out.println("total words: " + totalWords);
}
}
}
Output:
words per sentence: [4, 4, 7]
total words: 15
How it works:
- Each
Callable<Integer>counts the words in one sentence. invokeAll()returns only when all three are complete, so everyFutureis already done.- Because they are done,
resultNow()(Java 19+) can read each result without waiting and without a checked exception.
Real-World Example: A Price Comparison Service
A shopping app asks four vendors for the price of the same product at the same time. One vendor is down, one is too slow, and the app must still answer within 400 ms with the best price it received.
import java.util.ArrayList;
import java.util.Comparator;
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;
import java.util.concurrent.TimeUnit;
public class PriceComparison {
record Quote(String vendor, int priceRupees) { }
// Simulates an HTTP call to a vendor's price API
static Callable<Quote> askVendor(String vendor, long delayMs, int price, boolean down) {
return () -> {
Thread.sleep(delayMs);
if (down) {
throw new IllegalStateException(vendor + " service unavailable");
}
return new Quote(vendor, price);
};
}
public static void main(String[] args) throws InterruptedException {
List<String> vendors = List.of("ShopKart", "BuyNow", "MegaMart", "QuickBuy");
List<Callable<Quote>> requests = List.of(
askVendor("ShopKart", 150, 1299, false),
askVendor("BuyNow", 100, 0, true), // fails
askVendor("MegaMart", 1000, 1199, false), // too slow
askVendor("QuickBuy", 200, 1249, false));
List<Quote> quotes = new ArrayList<>();
try (ExecutorService executor = Executors.newFixedThreadPool(vendors.size())) {
// Unfinished requests are cancelled after 400 ms
List<Future<Quote>> answers = executor.invokeAll(requests, 400, TimeUnit.MILLISECONDS);
for (int i = 0; i < answers.size(); i++) {
Future<Quote> answer = answers.get(i);
String vendor = vendors.get(i);
if (answer.isCancelled()) {
System.out.printf("%-9s: timed out%n", vendor);
continue;
}
try {
Quote quote = answer.get();
quotes.add(quote);
System.out.printf("%-9s: Rs. %d%n", vendor, quote.priceRupees());
} catch (ExecutionException e) {
System.out.printf("%-9s: failed (%s)%n", vendor, e.getCause().getMessage());
}
}
}
quotes.stream()
.min(Comparator.comparingInt(Quote::priceRupees))
.ifPresentOrElse(
best -> System.out.println("Best price: " + best.vendor() + " at Rs. " + best.priceRupees()),
() -> System.out.println("No vendor answered in time"));
}
}
Output:
ShopKart : Rs. 1299
BuyNow : failed (BuyNow service unavailable)
MegaMart : timed out
QuickBuy : Rs. 1249
Best price: QuickBuy at Rs. 1249
How it works:
- One Callable per vendor.
askVendor()builds aCallable<Quote>that waits like a network call, then either returns aQuoterecord or throws an exception. - All requests in parallel. A pool with one thread per vendor runs all four at once, so the total wait is set by the 400 ms limit, not by the sum of the delays.
- Three outcomes per Future. A cancelled
Futuremeans the vendor timed out (MegaMart). AnExecutionExceptionmeans the vendor failed, andgetCause()gives the reason (BuyNow). Otherwiseget()returns the quote. - Best answer. The stream picks the lowest price among the vendors that answered. MegaMart's cheaper Rs. 1199 is ignored because it arrived too late.
Callable tasks run on thread pools like those described in Java Thread Pools. If a task does not need to return anything, a plain Runnable is still the simpler choice.