In Java, both Callable
and FutureTask
are related to asynchronous computation, but they serve different roles:
Callable
- Interface:
Callable
is a functional interface fromjava.util.concurrent
that represents a task which returns a result and can throw a checked exception. - Purpose: It defines a single
call()
method, allowing tasks to return results and handle exceptions. - Return Type: The
call()
method returns a value of a specified type. - Usage: Used as a task that can be submitted to an
ExecutorService
for asynchronous execution.
Example of a Callable:
Callable callableTask = () -> {
return "Task Result";
};
FutureTask
- Class:
FutureTask
is a concrete class that implementsRunnable
andFuture
and can be used to wrap aCallable
orRunnable
task. - Purpose: It represents a cancellable asynchronous computation, wrapping a
Callable
orRunnable
and providing aFuture
interface to retrieve the result. - Usage: You can create a
FutureTask
from aCallable
orRunnable
, then submit it to anExecutorService
or run it directly in a thread. - Control: It provides methods like
get()
(to retrieve the result),cancel()
(to cancel the task), andisDone()
(to check if the task is completed).
Example of a FutureTask:
Callable callableTask = () -> "Task Result";
FutureTask futureTask = new FutureTask<>(callableTask);
// Run FutureTask in a thread or submit it to an executor
new Thread(futureTask).start();
// Retrieve result
try {
String result = futureTask.get();
System.out.println("Result: " + result);
} catch (Exception e) {
e.printStackTrace();
}
Key Differences
Feature | Callable | FutureTask |
---|---|---|
Type | Interface | Concrete class (implements Runnable and Future ) |
Purpose | Defines a task that returns a result | Wraps a Callable or Runnable to execute asynchronously and control the result |
Execution | Submitted to an ExecutorService | Can be submitted to an ExecutorService or run in a thread directly |
Return Value | Defined by the call() method | Accessed by FutureTask.get() |
Control Methods | No control over task execution | Provides get() , cancel() , and isDone() for task control |
In summary, Callable
is used to define a task that can return a result, while FutureTask
wraps a Callable
or Runnable
and provides additional control over the task’s execution and result retrieval.