Callable & Future in simple words

Sometimes we have to run a long-running task in a separate thread and return the result once execution is complete. Using Java Runnable interface we can run a task, but the disadvantage is it does not return result once execution is complete.

Then how can we achieve this?

There are two interfaces available in java.util.concurrent package using them we can solve this problem.

Callable:

Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception.

The Callable task returns the implementation of Future interface, which is used for getting the result of an asynchronous operation. Its uses include providing a couple of methods to check whether the asynchronous execution is completed or not and retrieving the result of the computation.

The Callable interface is very similar to the Runnable interface. The main characteristics of this interface are:

  • It’s a generic interface. It has a single type parameter that corresponds to the return type of the call() method.
  • It declares the call() method. This method will be executed by the executor when it runs the task. It must return an object of the type specified in the declaration.
  • The call() method can throw any checked exception.

Future:

When you submit a Callable task to an executor service, it will return an implementation of the Future interface that allows you to control the execution and the status of the task and to get the result. The main characteristics of this interface are:

    • You can cancel the execution of the task using the cancel() method.
  • You can check whether the task has been cancelled
  • You can get the value returned by the task using the get() method.

Methods in Future interface:

FutureInterface.png

Example:

We will use two methods:

  • First, we will use the traditional way and implement the Callable interface.
  • Second, we will use the lambda expression to implement Callable.

In both method, we will submit 10 jobs to executer service and add them to the list of Future.  Once all task is done we will get the result and print it.

You can also check out the  code form git: Git Link

CallableService.java

Driver.java

 

One thought on “Callable & Future in simple words”

  1. Thanks for the sensible critique. Me and my neighbor were just preparing to do a little research on this. We got a grab a book from our local library but I think I learned more from this post. I am very glad to see such wonderful info being shared freely out there.

Leave a Reply

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