Middle
What is FutureTask in Java?
sobes.tech AI
Answer from AI
FutureTask is a class that implements the Runnable and Future interfaces, representing a cancellable asynchronous computation. It can be used to wrap Callable or Runnable objects and execute them in a thread.
Key features:
Runnable: Can be passed to threads or executors for execution.Future: Allows obtaining the computation result, checking its status (isDone()), cancelling (cancel()), and blocking until completion (get()).- Flexibility: Can be used both for wrapping existing
Runnableand for executing operations that return a result (Callable).
Example usage:
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ExecutionException;
// Task that returns a result
Callable<Integer> myCallable = () -> {
// Perform a long operation
Thread.sleep(1000);
return 42;
};
// Wrap Callable in FutureTask
FutureTask<Integer> futureTask = new FutureTask<>(myCallable);
// Create a thread to execute the task
Thread thread = new Thread(futureTask);
// Start the thread
thread.start();
try {
// Get the result (blocks until completion)
Integer result = futureTask.get();
System.out.println("Result: " + result); // Result: 42
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
// Check status
System.out.println("Task completed: " + futureTask.isDone()); // Task completed: true