Junior — Middle
In what cases is the Callable interface used in programming?
sobes.tech AI
Answer from AI
The Callable interface in Java is used when you need to execute a task that returns a result and can throw a checked exception. Unlike Runnable, which does not return a value and cannot throw checked exceptions, Callable allows:
- Running a task in a separate thread and obtaining the result via
Future. - Handling exceptions that may occur during execution.
Example of using Callable with ExecutorService:
import java.util.concurrent.*;
Callable<Integer> task = () -> {
// Some computational task
return 42;
};
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(task);
try {
Integer result = future.get();
System.out.println("Result: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
Thus, Callable is suitable for asynchronous tasks where the result and error handling are important.