On SO, I found all theoretical difference between Callable
and Runnable
and all are almost similar. But, I didn't understand why was Callable
introduced in later version ? What was the gap/flaws in Runnable, which Callable
is capable of doing ? Anyone can explain with scenario where Callable
is only solution ?
Callable has two differences. It can return a value or throw a checked exception.
This make a difference when using lambdas so that even though you don't specify which one to sue the compiler has to work it out.
// the lambda here must be a Callable as it returns an Integer
int result = executor.submit(() -> return 2);
// the lambda here must be a Runnable as it returns nothing
executors.submit(() -> System.out.println("Hello World"));
// the lambda here must be a Callable as an exception could be thrown
executor.submit(() -> {
try (FileWriter out = new FileWriter("out.txt")) {
out.write("Hello World\n");
}
return null; // Callable has to return something
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With