Junior — Middle
Have you used the Callable interface for executing tasks in Java?
sobes.tech AI
Answer from AI
Yes, the Callable interface in Java is used for executing tasks that return a result and can throw exceptions. Unlike Runnable, Callable allows you to obtain the result of execution through Future.
Example of using Callable:
import java.util.concurrent.*;
public class CallableExample {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Integer> task = () -> {
// Some computational task
Thread.sleep(1000);
return 123;
};
Future<Integer> future = executor.submit(task);
System.out.println("Task started");
Integer result = future.get(); // Waiting for the result
System.out.println("Result: " + result);
executor.shutdown();
}
}
This approach is convenient for asynchronous execution of tasks with the ability to get the result and handle exceptions.