Middle
What is the difference between the Runnable and Callable interfaces in Java?
sobes.tech AI
Answer from AI
The main difference is that Runnable cannot return a result and cannot throw a checked exception, whereas Callable can.
Runnable
- Method
run():void run(); - Does not return a value.
- Cannot throw a checked exception (those inheriting from
Exception, exceptRuntimeException). - Suitable for tasks that are simply executed without returning a result.
Callable
- Method
call():V call() throws Exception;(whereVis the return type). - Returns a value (type specified in
<V>). - Can throw a checked exception.
- Often used with
ExecutorServiceandFuturefor asynchronous task execution and retrieving their results.
Usage in ExecutorService:
Runnableis passed toexecute(Runnable task)orsubmit(Runnable task). Thesubmitmethod returns aFuture<?>.Callableis passed tosubmit(Callable<T> task). Thesubmitmethod returns aFuture<T>.
Example of Runnable:
// Example Runnable
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Runnable task running...");
}
}
Example of Callable:
// Example Callable
import java.util.concurrent.Callable;
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("Callable task running...");
return "Task completed";
}
}