Category: java
Callable and Future: The Relationship
Published on 27 Oct 2026
Explanation
Callable defines a task that returns a value. Future represents the result of an asynchronous computation and lets callers wait for completion, retrieve the result, cancel the task, or check its status.
Code:
import java.util.concurrent.*;
public class CallableFutureDemo {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newSingleThreadExecutor();
try {
Callable<String> task = () -> "Report ready";
Future<String> future = pool.submit(task);
System.out.println(future.get());
} finally { pool.shutdown(); }
}
}
Explanation
Unlike Runnable, Callable<T> has a call() method that returns T and may throw checked exceptions. It is useful for computations such as fetching a record or calculating a report total.
Code:
import java.util.concurrent.Callable;
public class CallableReturnDemo {
public static void main(String[] args) throws Exception {
Callable<Integer> calculation = () -> 7 * 6;
System.out.println(calculation.call());
}
}
Explanation
Future.get() blocks until the task completes unless a timed get is used. Avoid calling get() too early on tasks that could run concurrently, because doing so can eliminate the benefit of asynchronous execution.
Code:
import java.util.concurrent.*;
public class FutureGetDemo {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newSingleThreadExecutor();
try {
Future<String> f = pool.submit(() -> {
Thread.sleep(200);
return "Done";
});
System.out.println(f.get(1, TimeUnit.SECONDS));
} finally { pool.shutdown(); }
}
}
Explanation
isDone() checks whether a task has completed, while cancel(true) requests cancellation and may interrupt the executing thread. Tasks should respond to interruption for cancellation to work cooperatively.
Code:
import java.util.concurrent.*;
public class FutureCancelDemo {
public static void main(String[] args) {
ExecutorService pool = Executors.newSingleThreadExecutor();
Future<?> f = pool.submit(() -> {
try { Thread.sleep(5000); }
catch (InterruptedException e) { Thread.currentThread().interrupt(); }
});
f.cancel(true);
System.out.println("Cancelled: " + f.isCancelled());
pool.shutdownNow();
}
}
Explanation
Callable describes what a task does and what value it returns. Future describes how the caller interacts with the task's eventual outcome. An ExecutorService connects them by submitting the Callable and returning a Future.
Code:
import java.util.concurrent.*;
public class CallableFutureSummary {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newSingleThreadExecutor();
try {
Callable<Double> task = () -> Math.sqrt(81);
Future<Double> result = pool.submit(task);
System.out.println(result.get());
} finally { pool.shutdown(); }
}
}