Callable and Future

suggest change

While Runnable provides a means to wrap code to be executed in a different thread, it has a limitation in that it cannot return a result from the execution. The only way to get some return value from the execution of a Runnable is to assign the result to a variable accessible in a scope outside of the Runnable.

Callable was introduced in Java 5 as a peer to Runnable. Callable is essentially the same except it has a call method instead of run. The call method has the additional capability to return a result and is also allowed to throw checked exceptions.

The result of submitting a Callable is a Future.

Future can be considered a container of sorts that houses the result of the Callable computation. Computation of the callable can carry on in another thread, and any attempt to tap the result of a Future will block and will only return the result once it is available.

Callable Interface

public interface Callable<V> {
    V call() throws Exception;
}

Future

interface Future<V> {
    V get();
    V get(long timeout, TimeUnit unit);
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();
}

Using Callable and Future example:

public static void main(String[] args) throws Exception {
    ExecutorService es = Executors.newSingleThreadExecutor();
          
    System.out.println("Time At Task Submission : " + new Date());
    Future<String> result = es.submit(new ComplexCalculator());
    // Future.get() blocks until the result is available. This task sleeps 100 ms.
    System.out.println("Result of Complex Calculation is : " + result.get());
    System.out.println("Time At the Point of Printing the Result : " + new Date());
}

Our Callable that does a lengthy computation

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ComplexCalculator implements Callable<String> {

    @Override
    public String call() throws Exception {
        Thread.sleep(100);
        System.out.println("Calculation complete");
        return "Complex Result";
    }

    public static void main(String[] args) throws Exception {
        // var is Java 10+. Virtual threads need Java 21+.
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            Future<String> result = executor.submit(new ComplexCalculator());
            System.out.println("Result: " + result.get());
        }
    }
}
Calculation complete
Result: Complex Result

Other operations permitted on Future

While get() is the method to extract the actual result Future has provision

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents