Runnable Vs Callable in Java

Connect with

java8_logoLearn 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();
    }
    
  • The Runnable interface has a method run().
  • In the above interface you can see one method which neither throw any checked exception nor it returns anything.
  • It is being used to create a thread by implementing this 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 while Callable, added on in JDK 5.
  • A Callable interface has call() method while a Runnable interface has run() method.
  • A Callable can return a value while Runnable does not returns any .
  • A Callable can throw checked exception while a Runnable can not.
  • A Callable can be used with ExecutorService#invokeXXX() methods while Runnable can not be .
  • FutureTask is used along with Callable to get the result of asynchronous computation task performed in call() 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

Callable Java Oracle

I hope you enjoyed this post about Runnable vs Callable in Java, you can visit visit Java tutorial for more blog post.
Happy Learning! ๐Ÿ™‚


Connect with

Leave a Comment

Your email address will not be published. Required fields are marked *