We all know that we can create a thread either by extending the Thread class or by implementing the Runnable interface (see here). In both cases, we code our business logic in the run() method which has a return type void. It means we cannot return anything from the run() method. To support this feature, instead of the Runnable interface we can use Callable interface.
Callable vs Runnable
- When we implement Runnable, we implement its run() method which does not return anything. While in the case of Callable, we implement its call() method which returns a result.
- A tread cannot be created with a Callable, it can only be created with the Runnable.
- The call() method can throw an exception while the run() method cannot.
Future
When the call() method completes, its result must be stored in an object known to the main thread so that main thread can know about the result that thread returned. For this, a Future object can be used.
A Future object can be thought of an object that holds the result - it may not hold it right now but it will do so in the future - once the Callable returns.
Callable and Future do two different things - Callable like Runnable encapsulates the task that is supposed to run on another thread. On the other hand, a Future is used to store a result obtained from a different thread.
Code Example
Here, we are going to create a FactorialCalculator which is of type Callable. We will perform our computations in the call() method. This call() method will return the result which will be retrieved from the Future reference held by the main thread.
Output
The output of the above code is
Here we are sending the Callable object to the executor using the submit() method. This method receives a Callable object as a parameter and returns a Future object that we can use with two main objectives -
Factorial of 2 is: 2 Factorial of 5 is: 120 Future result is: 120 and Task done is: true Future result is: 2 and Task done is: true Factorial of 8 is: 40320 Future result is: 40320 and Task done is: true Factorial of 9 is: 362880 Future result is: 362880 and Task done is: true
- We can control the status of the task - we can cancel the task and check if it has finished. For this purpose, we have used the isDone() method to check if the task is finished.
- We can get the result returned by the call() - we are using get() method for this purpose. This method waits until the Callable object has finished the execution of the call() method and has returned its result.
Conclusion
Congratulations!! ๐ today we discussed Callable and Future and their implementations. I hope you enjoyed this post.
Comments
Post a Comment