Understanding Callable, ExecutorService, and Future in Java
This article explains how Java's Callable interface, ExecutorService, and Future work together to execute asynchronous tasks, detailing their API relationships, internal implementations, and practical usage examples with code snippets illustrating task creation, submission, and result retrieval.
Java provides three primary ways to create threads: extending Thread, implementing Runnable, and implementing Callable. The Callable interface differs from Runnable by returning a result via a Future and allowing checked exceptions.
The article focuses on two questions: how the call() method is executed and how the task result is obtained.
Key concepts: Callable – a generic interface with a single V call() method that returns a value. Executor – defines void execute(Runnable command). ExecutorService – extends Executor and adds submit() methods that return Future objects. Future – represents the asynchronous computation result and provides methods such as get(), cancel(), isDone(). FutureTask – a concrete class implementing RunnableFuture, wrapping a Callable (or Runnable) and managing execution state.
Relevant source snippets:
public interface Callable<V> {
V call() throws Exception;
}
public interface Runnable {
void run();
} public interface Executor {
void execute(Runnable command);
}
public interface ExecutorService extends Executor {
<T> Future<T> submit(Callable<T> task);
Future<?> submit(Runnable task);
<T> Future<T> submit(Runnable task, T result);
// other lifecycle methods omitted for brevity
} FutureTaskimplements RunnableFuture and internally stores the Callable, the execution state, and the outcome (result or exception). Its run() method invokes call(), captures the result or exception, and updates the state accordingly.
public class FutureTask<V> implements RunnableFuture<V> {
private Callable<V> callable;
private Object outcome; // result or exception
private volatile int state;
// state constants: NEW, COMPLETING, NORMAL, EXCEPTIONAL, CANCELLED, ...
public void run() {
if (callable != null && state == NEW) {
try {
V result = callable.call();
set(result);
} catch (Throwable ex) {
setException(ex);
}
}
}
public V get() throws InterruptedException, ExecutionException {
// await completion and return or throw based on state
}
}The article also shows an adapter class that turns a Runnable into a Callable:
static final class RunnableAdapter<T> implements Callable<T> {
final Runnable task;
final T result;
RunnableAdapter(Runnable task, T result) { this.task = task; this.result = result; }
public T call() { task.run(); return result; }
}Practical example:
class MyTask implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("子线程开始计算...");
for (int i = 0; i < 3; ++i) {
Thread.sleep(1000);
System.out.println("子线程计算中,用时 " + (i + 1) + " 秒");
}
System.out.println("子线程计算完成,返回:100");
return 100;
}
}
ExecutorService executor = Executors.newCachedThreadPool();
MyTask task = new MyTask();
// Using Future
Future<Integer> future = executor.submit(task);
System.out.println("主线程得到返回结果:" + future.get());
// Using FutureTask
FutureTask<Integer> futureTask = new FutureTask<>(task);
executor.submit(futureTask);
System.out.println("主线程得到返回结果:" + futureTask.get());
executor.shutdown();Both approaches produce the same output; the difference lies in which submit overload is used ( submit(Callable) vs. submit(Runnable)), but ultimately the task is executed via execute(futureTask).
In summary, the submit() method wraps a Callable inside a FutureTask, passes it to the thread pool's execute(), and the FutureTask manages execution state, result storage, and provides the Future interface for result retrieval.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Full-Stack Internet Architecture
Introducing full-stack Internet architecture technologies centered on Java
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
