Junior — Middle
Can you explain what the FutureTask class in Java is and how it is used for asynchronous tasks?
sobes.tech AI
Answer from AI
The FutureTask class in Java represents an implementation of the Future and Runnable interfaces, allowing asynchronous tasks to be executed and their results to be retrieved in the future.
Main features:
- Allows running a task in a separate thread.
- Enables obtaining the execution result via the
get()method, which blocks until the task is complete. - Supports cancellation of execution.
Example of usage:
import java.util.concurrent.*;
Callable<Integer> callable = () -> {
// Long operation
Thread.sleep(1000);
return 42;
};
FutureTask<Integer> futureTask = new FutureTask<>(callable);
Thread thread = new Thread(futureTask);
thread.start();
// Other operations can be performed here
try {
Integer result = futureTask.get(); // Waits for completion and retrieves the result
System.out.println("Result: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}