Senior
What is the difference between the Callable and Runnable interfaces? Why are they called differently?
sobes.tech AI
Answer from AI
The Runnable and Callable interfaces in Java are used to describe tasks that can be executed in separate threads, but they have key differences:
-
Runnable:
- The
run()method does not return a result and does not throw checked exceptions. - Used for tasks where a result is not needed.
- Signature:
void run().
- The
-
Callable<V>:
- The
call()method returns a result of typeV. - Can throw checked exceptions.
- Used when you need to obtain the result of the task or handle exceptions.
- Signature:
V call() throws Exception.
- The
Why are they named differently:
- Runnable — "something that can be run" (run — to execute), emphasis on execution without a result.
- Callable — "something that can be called" (call — to invoke), emphasis on invocation with a return value.
Example of using Callable with ExecutorService:
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
return 123;
};
Future<Integer> future = executor.submit(task);
System.out.println("Result: " + future.get());
executor.shutdown();
}
}