I have understood the difference between Runnable
and Callable
interface in Java. From Java 1.5 additional features has been added to Runnable
interface and has been called Callable
in order to maintain backward compatibility.
My questions is now that we have Callable
interface, shall we always use that? What are the use cases of not using Callable
and using Runnable
?
(This is a good article on what are the differences between them)
A callable interface throws the checked exception and returns the result. A runnable interface, on the other hand, shows the result or throws an exception, but does not do both.
A callable interface was added in Java 5 to complement the existing Runnable interface, which is used to wrap a task and pass it to a Thread or thread pool for asynchronous execution. Callable actually represents an asynchronous computation, whose value is available via a Future object.
The Callable interface is similar to Runnable, in that both are designed for classes whose instances are potentially executed by another thread. A Runnable, however, does not return a result and cannot throw a checked exception.
Both have their uses, and both are supported by the Executor framework in java.util.concurrent. Runnable has been around longer, but it is still in use and not discouraged.
Callables can throw exceptions and return values, which makes them the better abstraction for result-bearing tasks (such as fetching a resource from the network, performing an expensive computation of a value, and the like) [from Java Concurrency in Practice by Goetz, Bloch et. al., the standard work on Java concurrency].
So, if you are designing an API, I would suggest using Callables when possible. If you are sure that the tasks will not return values and will not throw exceptions, then Runnables are also a valid choice. There is no black and white here, especially because Runnables can easily be wrapped in Callables and vice versa.
As an aside, note that your Callable implementation need not declare throws Exception
; the fact that Callable itself declares it is only to allow implementors to throw any checked exceptions. Callers of your Callable who rely solely on the Callable interface will have to write exception handling code, though.
Also note that Callables need not return a value; you can simply declare your Callable to return Void
(with capital 'V
').
IMHO, Runnable is a better type to use when taking as argument a function which
Don't forget that Callable.call()
throws Exception. That means that if you take a Callable as argument, this Callable can throw any kind of exception, and you must have a way to handle them all in a correct way. If you can't do that, it's better to let the implementor of the Callable handle the exception as he wants to, and make the argument a Runnable to make that clear.
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