Multithreading with Callable and Future in Java

Multithreading is the notion of handling program actions that do not take place in the program’s main Thread, which is handled by many different Threads. This concept will make the processing of the program faster. We have many ways to implement multithreading in Java, but in this tutorial, I only introduce to you all about Callable and Future in Java with the ability to return result after processing and can throw an exception if in during processing, there is an error.

OK, let’s get started …

First, I will create a new project for example:

Multithreading with Callable and Future in Java

Callable is an interface that uses Java Generic to define the object that will be returned after processing the task. Here, I will take the example of the sum of two numbers, but instead of handling this sum in the main thread of the program, I will use Callable to process in another thread.

Its Callable object will have the following content:

To execute Callable’s task, we must submit it to a Thread Pool using the submit() method of the Executor Framework.

Now, I will create the main class for the above example with the following content:

With the code above, we just stop at the level submiting a Callable object to the Thread Pool to handle the task. How to get the results after processing is completed? If you notice, you will see that the return object of the submit() method is a Future object. Using this Future object, we can manage the status of the Callable task and retrieve returned object of the Callable object.

To get the result returned object with the Future object, we will use its get() method to wait until the Callable operation completes and returns the result.

Result:

Multithreading with Callable and Future in Java

The get() method is synchronous, so it will block our program every time we wait for the result of Callable. To limit the risk of blocking the program too long, we can use this get() method with a timeout like below:

In addition, we can use the isDone(), isCancelled() method of the Future object to find out the current status of the Callable object that it is currently monitoring.

2 thoughts on “Multithreading with Callable and Future in Java

  1. “I will create a new thread using Callable to process.” This statement is not correct. You get thread from a thread pool using Executors and submit Callable task to be executed by that thread.

Add Comment