Difference between Callable and FutureTask in Java

In Java, both Callable and FutureTask are related to asynchronous computation, but they serve different roles:

Callable

  • Interface: Callable is a functional interface from java.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 implements Runnable and Future and can be used to wrap a Callable or Runnable task.
  • Purpose: It represents a cancellable asynchronous computation, wrapping a Callable or Runnable and providing a Future interface to retrieve the result.
  • Usage: You can create a FutureTask from a Callable or Runnable, then submit it to an ExecutorService or run it directly in a thread.
  • Control: It provides methods like get() (to retrieve the result), cancel() (to cancel the task), and isDone() (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

FeatureCallableFutureTask
TypeInterfaceConcrete class (implements Runnable and Future)
PurposeDefines a task that returns a resultWraps a Callable or Runnable to execute asynchronously and control the result
ExecutionSubmitted to an ExecutorServiceCan be submitted to an ExecutorService or run in a thread directly
Return ValueDefined by the call() methodAccessed by FutureTask.get()
Control MethodsNo control over task executionProvides 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.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *