Middle
What is the Callable interface in Java?
sobes.tech AI
Answer from AI
The Callable interface in Java represents a task that can be executed in a separate thread and returns a result. Unlike Runnable, which does not return a value and cannot throw checked exceptions, Callable<V> returns an object of type V and can throw exceptions.
Main features:
- The
call()method returns the execution result. - Can be used with
ExecutorServicefor asynchronous task execution and obtaining results viaFuture.
Example usage:
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 42;
};
Future<Integer> future = executor.submit(task);
// Can perform other operations
Integer result = future.get(); // blocks until the task completes
System.out.println("Result: " + result);
executor.shutdown();
}
}