Java Callable Interface

Su Suriya Ravichandran Updated 18 Nov 2026
11 min read ·Lesson 195 of 306

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.

RunnableCallable<V>
Packagejava.langjava.util.concurrent
Methodvoid run()V call() throws Exception
Returns a valueNoYes, of type V
Can throw checked exceptionsNoYes
Can be passed to new Thread(...)YesNo (wrap it in a FutureTask)
Used with ExecutorServiceexecute() 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 a String, so it matches Callable<String>.
  • greeting.call() simply runs the method. No new thread is involved.
  • main declares throws Exception because call() 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:

  • PrimeCounter implements Callable<Integer>, so call() must return an Integer. The int count is auto-boxed.
  • submit() starts the task on the pool thread and immediately returns a Future<Integer>. main keeps running and prints its message.
  • primes.get() blocks until call() has finished, then returns its value.
  • call() here throws nothing, so the throws Exception clause 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 each Future in 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 Runnable lambda could not call Files.readString() without a try/catch, because run() cannot throw checked exceptions. A Callable can.
  • The file does not exist, so call() throws NoSuchFileException, which is a subclass of IOException.
  • get() wraps it in an ExecutionException. getCause() gives you back the real exception so you can handle it.

Note: Future.get() can throw two checked exceptions: ExecutionException when the task failed, and InterruptedException when 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 throws TimeoutException. The task keeps running until it is cancelled.
  • cancel(true) interrupts the worker thread, so Thread.sleep() inside the task ends with an InterruptedException.
  • A cancelled Future counts as done. Calling get() on it would throw a CancellationException.
Future methodPurpose
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:

  • FutureTask wraps the Callable. Its run() method calls call() and stores the result.
  • The thread runs the FutureTask like any other Runnable.
  • task.get() waits for the thread to finish and returns the stored Long. 20! is the largest factorial that fits in a long.

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 every Future is 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:

  1. One Callable per vendor. askVendor() builds a Callable<Quote> that waits like a network call, then either returns a Quote record or throws an exception.
  2. 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.
  3. Three outcomes per Future. A cancelled Future means the vendor timed out (MegaMart). An ExecutionException means the vendor failed, and getCause() gives the reason (BuyNow). Otherwise get() returns the quote.
  4. 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Callable Interface and get answers drawn from it.

Signed-in readers only.