Skip to main content

Asynchronous execution using CompletableFuture in java


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 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 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 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.


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.


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()
        .filter(s->{return s!=null && s.length()>0;})

     } catch (Exception e) {
     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
   System.out.println("print: start");
   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
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");
   System.out.println("print: start");
   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
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:-

Below are few lines from "numbers.txt" which I have used to read the numbers from.

If you interested then you can check my other post on sequential executions:


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 "" 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

Why HashMap key should be immutable in java

HashMap is used to store the data in key, value pair where key is unique and value can be store or retrieve using the key. Any class can be a candidate for the map key if it follows below rules. 1. Overrides hashcode() and equals() method.   Map stores the data using hashcode() and equals() method from key. To store a value against a given key, map first calls key's hashcode() and then uses it to calculate the index position in backed array by applying some hashing function. For each index position it has a bucket which is a LinkedList and changed to Node from java 8. Then it will iterate through all the element and will check the equality with key by calling it's equals() method if a match is found, it will update the value with the new value otherwise it will add the new entry with given key and value. In the same way it check for the existing key when get() is called. If it finds a match for given key in the bucket with given hashcode(), it will return the value other

jaxb2-maven-plugin to generate java code from XSD schema

In this tutorial I will show how to generate the Java source code from XSD schema. I will use jaxb2-maven-plugin to generate the code using XSD file which will be declared in pom.xml to make it part of build, so when maven build is executed it will generate the java code using XSD. Class generation can be controlled in plugin configuration. Maven changes (pom.xml) Include below plugin in your pom.xml. Here we have done some configuration under configuration section as given below. schemaDirectory : This is the directory where I keep my schema (XSD file). outputDirectory : This is the java source location where I want to generate the Java files. If it is not given then by default it will be generate inside target folder. clearOutputDir : If this property is true then it will generate the classes on each build otherwise it will generate only if output directory is empty. <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>jaxb2-maven-plugin</art