Middle
What is the Callable interface in Java?
sobes.tech AI
Answer from AI
Callable is an interface in Java that represents a task which returns a result and can throw an exception. Unlike the Runnable interface, which simply executes code, Callable is designed for asynchronous computations where the result is important.
Main features:
- Return value: The
call()method returns a value of the type specified by the generic<V>. - Exception handling: The
call()method can declare and throw exceptions. - Integration with
ExecutorService:Callableis often used with thread pools (ExecutorService) to execute tasks and obtain aFuturefor managing the result.
Example usage:
// Implementation of Callable
import java.util.concurrent.Callable;
public class MyCallableTask implements Callable<String> {
private final int taskId;
public MyCallableTask(int taskId) {
this.taskId = taskId;
}
@Override
public String call() throws Exception {
// Simulate execution of a complex task
Thread.sleep(1000);
System.out.println("Task " + taskId + " completed in thread: " + Thread.currentThread().getName());
return "Result of task " + taskId;
}
}
// Usage with ExecutorService
import java.util.concurrent.*;
public class CallableExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2); // Create thread pool
// Create Callable tasks
Callable<String> task1 = new MyCallableTask(1);
Callable<String> task2 = new MyCallableTask(2);
// Submit tasks for execution and get Futures
Future<String> future1 = executorService.submit(task1);
Future<String> future2 = executorService.submit(task2);
try {
// Retrieve results (blocking call)
String result1 = future1.get();
String result2 = future2.get();
System.out.println("Result of task 1: " + result1);
System.out.println("Result of task 2: " + result2);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
executorService.shutdown(); // Properly shutdown thread pool
}
}
}
Differences between Callable and Runnable:
| Characteristic | Runnable | Callable |
|---|---|---|
| Return value | No (run() method void) |
Yes (call() returns <V>) |
| Exception handling | Cannot throw checked exceptions (catch or Unchecked) | Can throw checked exceptions |
| Launch method | run() |
call() |
| Integration with Future | No | Yes (via ExecutorService.submit()) |