The difference between the Runnable and Callable interfaces in Java
See explanation here.
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.
What are the differences in the applications of
Runnable
andCallable
. Is the difference only with the return parameter present inCallable
?
Basically, yes. See the answers to this question. And the javadoc for Callable
.
What is the need of having both if
Callable
can do all thatRunnable
does?
Because the Runnable
interface cannot do everything that Callable
does!
Runnable
has been around since Java 1.0, but Callable
was only introduced in Java 1.5 ... to handle use-cases that Runnable
does not support. In theory, the Java team could have changed the signature of the Runnable.run()
method, but this would have broken binary compatiblity with pre-1.5 code, requiring recoding when migrating old Java code to newer JVMs. That is a BIG NO-NO. Java strives to be backwards compatible ... and that's been one of Java's biggest selling points for business computing.
And, obviously, there are use-cases where a task doesn't need to return a result or throw a checked exception. For those use-cases, using Runnable
is more concise than using Callable<Void>
and returning a dummy (null
) value from the call()
method.
- A
Callable
needs to implementcall()
method while aRunnable
needs to implementrun()
method. - A
Callable
can return a value but aRunnable
cannot. - A
Callable
can throw checked exception but aRunnable
cannot. A
Callable
can be used withExecutorService#invokeXXX(Collection<? extends Callable<T>> tasks)
methods but aRunnable
cannot be.public interface Runnable { void run(); } public interface Callable<V> { V call() throws Exception; }