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

Setting up kerberos in Mac OS X

Kerberos in MAC OS X Kerberos authentication allows the computers in same domain network to authenticate certain services with prompting the user for credentials. MAC OS X comes with Heimdal Kerberos which is an alternate implementation of the kerberos and uses LDAP as identity management database. Here we are going to learn how to setup a kerberos on MAC OS X which we will configure latter in our application. Installing Kerberos In MAC we can use Homebrew for installing any software package. Homebrew makes it very easy to install the kerberos by just executing a simple command as given below. brew install krb5 Once installation is complete, we need to set the below export commands in user's profile which will make the kerberos utility commands and compiler available to execute from anywhere. Open user's bash profile: vi ~/.bash_profile Add below lines: export PATH=/usr/local/opt/krb5/bin:$PATH export PATH=/usr/local/opt/krb5/sbin:$PATH export LDFLAGS=&

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

Multiple data source with Spring boot, batch and cloud task

Here we will see how we can configure different datasource for application and batch. By default, Spring batch stores the job details and execution details in database. If separate data source is not configured for spring batch then it will use the available data source in your application if configured and create batch related tables there. Which may be the unwanted burden on application database and we would like to configure separate database for spring batch. To overcome this situation we will configure the different datasource for spring batch using in-memory database, since we don't want to store batch job details permanently. Other thing is the configuration of  spring cloud task in case of multiple datasource and it must point to the same data source which is pointed by spring batch. In below sections, we will se how to configure application, batch and cloud task related data sources. Application Data Source Define the data source in application properties or yml con

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