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
Runnableinterface is in JDK 1.0 whileCallable, added on in JDK 5. - A
Callableinterface hascall()method while aRunnableinterface hasrun()method. - A
Callablecan return a value whileRunnabledoes not returns any . - A
Callablecan throw checked exception while aRunnablecan not. - A
Callablecan be used withExecutorService#invokeXXX()methods whileRunnablecan not be . FutureTaskis used along withCallableto 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! ๐