Both Callable and Runnable are interfaces used to define task supposed to be executed by a separate thread.Also, both of them can be used with lambda expressions. But there are key differences between the two interfaces.
- Callable interface can return the result of the task defined to be executed whereas Runnable does not return any result .Callable return a Future object which has methods to fetch the result of the task, check if the task has been completed or cancelled etc.
- Callable can throw checked exceptions whereas Runnable does not throw any exceptions.
- Callable is a functional interface which is added in Java 1.5 whereas Runnable exists since Java 1.0
- Callable has call() method which needs to be overriden to define the task whereas Runnable has run() method which needs to be overriden
- You can not pass the Callable to a Thread ,the way you pass the Runnable Object.You need to use the ExecutorService interface to execute the Callable interface.The interface defines the submit method which takes the Callable object and return a Future Object to retrieve the result.
Since runnable interface does not return any result so future.get() method returns null.
In case of callable return the result of the task which is retrieved by future.get() method.
Future has several API to help us with the processing task.
Future.isDone() method tells us if the task has been processed or not.If the task is processed it returns true else false.
Future.get() method returns the actual result of the task being processed.This method blocks the execution until the task is complete.
Future.cancel() method stop the execution of the task and interrupts its underlying thread.If we try to call Future.get() method after the cancel() method ,CancellationException is thrown.
Future.isCancelled() method tells if a future is already cancelled. It return true if it was cancelled .
References:- Java 8 API Documentation
That’s all about Runnable , Callable and Future interface.Happy Coding 🙂