Junior — Middle
What is the relationship between the Future and Callable interfaces in programming languages?
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.
The Future interface represents the result of an asynchronous operation, allowing you to check if the task is complete, get the result, or cancel the execution.
The relationship between them:
- Callable is used to describe a task that needs to be executed.
- Future is returned when submitting a Callable for execution (for example, via ExecutorService), and allows you to obtain the result of the Callable in the future.
Example:
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Integer> task = () -> {
Thread.sleep(1000);
return 123;
};
Future<Integer> future = executor.submit(task);
// ...
Integer result = future.get(); // blocks until the task is complete
executor.shutdown();