Learn Runnable Vs Callable in Java. Different aspects of Java Runnable and callable example.
1. Overview of Runnable Vs Callable in Java
Runnable and Callable are the two interfaces in Java which is widely used.
The Callable
interface is newer than Runnable
interface and added on JDK 5 release. You know, there are major feature release in JDK 5 in which a lot of new things introduced e.g. Generics collection, Enum, Static imports and variable argument method etc. Although both Callable
and Runnable
interface are designed to represent a task, which can be executed by any thread.
This is one of the important interview questions to check whether the candidate aware of the multi-threading basic things or not. This is one of the interesting questions too. And you can say itโs a very popular interview question in various Java Interviews at all levels.
2. Key points of Runnable
- Interface class
public interface Runnable { void run(); }
Runnable
interface has a method run()
.Runnable
interface.3. Key points of Callable
public interface Callable<v> { V call() throws Exception; }
- The Callable is a interface which has one method i.e. call().
- call() method return some Future value
- and it throws Exception it means it throws Checked exception.
- This Callable is a template based class which accept type of Future
4. Difference Between Callable and Runnable
- The
Runnable
interface is in JDK 1.0 whileCallable
, added on in JDK 5. - A
Callable
interface hascall()
method while aRunnable
interface hasrun()
method. - A
Callable
can return a value whileRunnable
does not returns any . - A
Callable
can throw checked exception while aRunnable
can not. - A
Callable
can be used withExecutorService#invokeXXX()
methods whileRunnable
can not be . FutureTask
is used along withCallable
to get the result of asynchronous computation task performed incall()
method.
Another significant difference between Runnable
and Callable
interface has ability to throw checked exception, why so , just because of call()
method throw checked exception.
5. Reference
I hope you enjoyed this post about Runnable vs Callable in Java, you can visit visit Java tutorial for more blog post.
Happy Learning! ๐