Skip to main content

Asynchronous execution using CompletableFuture in java

CompletableFuture

CompletableFuture was introduced in Java 8 to support the asynchronous execution and avoid blocking calls. It implements Future and CompletionStage interfaces. Future can be used to retrieve the value and status of current task while CompletionStage provides multiple methods to support the event based task execution which helps in creating a chain or pipeline for the actions to happen during specified events.

Runnable


Runnable interface has a void run() method where we can write the logic which we want to execute but it can not return any result. Runnable can be executed using Thread or ExecutorService.
public abstract void run();
When we need to execute some tasks where we don't need to wait to get some result back then we can use Runnable. We just execute our task and do other work as we don't depend on the result of the task. Like if we want to write some logs asynchronously then we can use Runnable interface and execute without waiting for it's completion. Even Callable also can be used for same purpose.

Callable

Callable has call() method which can return a result and can throw exception also. Callable can be executed using ExecutorService.
    V call() throws Exception;
When we need to perform some task after one task's completion then this task depends upon the result of another tasks. In this scenario we can use Callable as it returns a result which we can pass to dependent task to start with. Like similar to producer/consumer problem where consumer waits for producer to complete so it can utilise the produced value to consume.
When callable is submitted for execution to ExecutorService, it returns instance of Future<V> with generic value.

Future

Future provides several method to get the status of current Callable task. Also it can be used to cancel the task or get the result of task upon completion. We can call the get() method to get the result of Callable task but it will block the execution and no other code will execute until the task is completed which behaves like synchronous execution.

Problem

We just saw when to use Runnable and when Callable. Also we know the problem of blocking with Callable when getting results using Future. To resolve this issue we needed something where we can tell the task, what is next thing you need to do once you finished the job. So we don't need to wait till it's completion but we will tell it what is next and when the task is completed, it will do the other job in the order as we specified. Here comes the CompletableFuture, using which we create a pipeline or chain of tasks in asynchronous manner.

Usage scenario 

Now we will define a problem to solve it using Future and CompletableFuture.

Suppose we have a file which contains some numbers on each line. We need to find out the largest number in one thread from this file and then print it to the console in another thread.

Solution

If we break the problem then it looks like some supplier consumer problem where one thread is supplying the largest number and another thread print it to console. Below is our coding solution which depicts this behaviour and tries to solve the problem in two different ways using Future and CompletableFuture.

Supplier code

Below is the code for supplier which reads the file and gives largest number. We use the same supplier code for both the cases (Future & CompletableFuture).
private Supplier<Integer> findLargestNum()throws Exception{
   System.out.println("findLargestNum: start");

   return ()->{
      Integer result = null;

      try {

         result = Files.readAllLines(Paths.get(Thread.currentThread()
        .getContextClassLoader()
        .getResource("numbers.txt").toURI()))
        .stream()
        .filter(s->{return s!=null && s.length()>0;})
        .mapToInt(s->Integer.parseInt(s))
        .max().orElse(0);

     } catch (Exception e) {
       e.printStackTrace();
     }
     System.out.println("findLargestNum: end");
     return result;
  };
}

Using Callable and Future (Blocking)

Now will see how it works with Callable and Future. Here I have put S.O.P. statements to see the ordering of execution. Here we can see that "maxNumFut.get()" is making blocking call which will not let the further lines execute until the tread is complete.
System.out.println("testCallable: start");
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> maxNumFut = executor.submit(()->{
   return findLargestNum().get();//calling get on supplier to execute the supplier code
});

Integer maxNum = maxNumFut.get();//blocking call
executor.execute(()->{
   System.out.println("print: start");
   System.out.println(maxNum);
   System.out.println("print: end");
});
System.out.println("testCallable: end");
Below is the output of the above code. If you notice here that the S.O.P. highlighted in bold are from the code where it reads the file and finds largest number. This block has executed in synchronous way and has blocked the execution of other code otherwise you might have seen that "testCallable: end" statement could have been printed earlier.
testCallable: start
findLargestNum: start
findLargestNum: end
testCallable: end
print: start
334556
print: end

Using CompletableFuture (Non-Blocking)

With CompletableFuture it is very easy to create the chain of tasks which execute in specified order asynchronously which we will see in below code.
System.out.println("testCompletable: start");
CompletableFuture.supplyAsync(findLargestNum())
.thenAccept((s->{
   System.out.println("print: start");
   System.out.println(s);
   System.out.println("print: end");
}));

System.out.println("testCompletable: end");


In above code at line#2 we used "supplyAsync" which takes a supplier and executes asynchronously using fork join pool and returns an instance of CompletableFuture. Then we have called "thenAccept" which takes a consumer and can access the output of previous task. We have provided consumer as lambda expression here where "s" is the output from previous task's output.
Now see the below output of above code where it shows the non-blocking execution.
testCompletable: start
findLargestNum: start
testCompletable: end
findLargestNum: end
print: start
334556
print: end

If you notice the line#3 is coming between the supplier code execution which provide it to be non-blocking. CompletableFutrue provides many methods to build this asynchronous chain of tasks, for example:-
CompletableFutrue.suplyAsync(....)
.thenApplyAsync(...)
.thenApplyAsync(...)
.thenAccept(...)

Below are few lines from "numbers.txt" which I have used to read the numbers from.
22
34
234
52
223
11
24
2
42
323

232
....
If you interested then you can check my other post on sequential executions: https://www.thetechnojournals.com/2019/11/executing-chain-of-tasks-sequentially.html

Comments

Popular Posts

SpringBoot - @ConditionalOnProperty example for conditional bean initialization

@ConditionalOnProperty annotation is used to check if specified property available in the environment or it matches some specific value so it can control the execution of some part of code like bean creation. It may be useful in many cases for example enable/disable service if specific property is available. Below are the attributes which can be used for property check.
havingValue - Provide the value which need to check against specified property otherwise it will check that value should not be false.matchIfMissing - If true it will match the condition and execute the annotated code when property itself is not available in environment.name - Name of the property to be tested. If you want to test single property then you can directly put the property name as string like "property.name" and if you have multiple properties to test then you can put the names like {"prop.name1","prop.name2"}prefix - It can be use when you want to apply some prefix to all prop…

Asynchronous REST service implementation in Spring boot

In this tutorial we will see how to create an asynchronous REST service endpoint using Spring boot application.
Asynchronous service works in a way that it will not block the client request and do the processing in separate thread. When work is complete the response returned to the client so our service will be able to handle more client requests at the same time, compare to synchronous processing model.
Let's understand how it is working in synchronous mode. In such server/client application at server side it has a pool of threads which are serving the request. If a request received by a thread then it will be blocked until it send the response back to client. In this case if processing doesn't take much time it will be able to process it quickly and accept other client requests but there could be one situation when all threads are busy and not able to accept the new client requests.

To overcome of such problems, asynchronous processing model introduced for REST services. In…

Entity to DTO conversion in Java using Jackson

It's very common to have the DTO class for a given entity in any application. When persisting data, we use entity objects and when we need to provide the data to end user/application we use DTO class. Due to this we may need to have similar properties on DTO class as we have in our Entity class and to share the data we populate DTO objects using entity objects. To do this we may need to call getter on entity and then setter on DTO for the same data which increases number of code line. Also if number of DTOs are high then we need to write lot of code to just get and set the values or vice-versa.
To overcome this problem we are going to use Jackson API and will see how to do it with minimal code only.
Maven dependency <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.9</version> </dependency> Entity class Below is our ent…

Web scraper using JSoup and Spring Boot

What is webscraping Webscraping is a technique to extract or pull the data from a website to gather required information by parsing the HTML source of their websites, such as articles from news or books site, products information from online shopping sites or course information from education sites. There are many organisations who uses web scraper to provide the best experience to their customers, for example extract the price for a smartphone from multiple online websites and show their customers the best and cheap product URL.
We will learn here how to code a web scraper by developing a simple new scraper service.
News scraper News scraper is used to extract the news articles or other related contents from a news site. Here we are going to create a web scraper application to pull the articles from news site.
Below are the operations provided by our news scraper service.
List all the authorsSearch articles by author nameSearch articles by article titleSearch articles by article desc…