Reputation: 31417
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 ?
Upvotes: 3
Views: 1747
Reputation: 533560
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
});
Upvotes: 3
Reputation: 10652
Well, the documentation does answer a big part of your question:
The
Callable
interface is similar toRunnable
, in that both are designed for classes whose instances are potentially executed by another thread. ARunnable
, however, does not return a result and cannot throw a checked exception.
So, you are jusing Callable instead of Runnable, if...
For example...
ExecutorService service = ... some ExecutorService...;
Callable<Integer> myCallable = new MyCallable( ... some parameters ... );
Future<Integer> future = service.submit( myCallable );
...
Integer myResult = future.get(); // will wait and return return value from callable as soon as done
Upvotes: 0