Junior — Middle
How do the Callable and Future interfaces in Java interact for asynchronous operations?
sobes.tech AI
Answer from AI
In Java, the Callable interface represents a task that returns a result and can throw exceptions. It is similar to Runnable but with the ability to return a value.
Future is an object that represents the result of an asynchronous operation running in another thread. With Future, you can check if the task has completed, get the result, or cancel the execution.
Together, Callable and Future are used to execute tasks asynchronously with the ability to obtain the result later. For example, you can submit a Callable for execution via ExecutorService and get a Future:
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Integer> task = () -> {
// some long operation
Thread.sleep(1000);
return 42;
};
Future<Integer> future = executor.submit(task);
// ... elsewhere in the code
if (future.isDone()) {
Integer result = future.get();
System.out.println("Result: " + result);
}
executor.shutdown();
Thus, Callable describes a task with a result, and Future allows managing and retrieving the result of this task asynchronously.