Runnable vs Callable in Java
Introduction
In Java concurrency, both Runnable and Callable are used to define tasks that can be executed by threads or thread pools.
While they look similar, they serve different purposes. Understanding their differences is crucial for interviews and real-world applications.
Runnable
Runnable is a functional interface introduced in Java 1.0. It represents a task that can be executed by a thread but does not return a result or throw checked exceptions.
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Task running...");
}
}
public class RunnableDemo {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
}
}
Callable
Callable<V> is a generic functional interface introduced in Java 5. It represents a task that returns a result and can throw checked exceptions.
Callable tasks are executed via ExecutorService and return a Future.
import java.util.concurrent.*;
class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
return "Task completed!";
}
}
public class CallableDemo {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new MyCallable());
System.out.println(future.get()); // prints "Task completed!"
executor.shutdown();
}
}
Comparison Table
| Aspect | Runnable | Callable |
|---|---|---|
| Return Value | Does not return a result | Returns a result via Future |
| Exceptions | Cannot throw checked exceptions | Can throw checked exceptions |
| Introduced | Java 1.0 | Java 5 |
| Execution | Run directly in a Thread |
Submitted to ExecutorService |
| Use Case | Simple tasks without results | Tasks that produce results or may throw exceptions |
Interview-Ready Notes
- Key Difference: Runnable is void-returning; Callable returns a value.
- Exceptions: Callable can throw checked exceptions; Runnable cannot.
- Best Practice: Use Callable when you need results or exception handling; Runnable for fire-and-forget tasks.
- Common Question: βWhy was Callable introduced?β β To support tasks that return results and handle checked exceptions in concurrent programming.
Conclusion
Runnable and Callable are both essential for Java concurrency. Runnable is simple and suited for tasks that donβt return results, while Callable is powerful for tasks that need to return values or handle exceptions. In interviews, emphasize their differences in return type, exception handling, and execution model.