{{announcement.body}}
{{announcement.title}}

Java 8 Parallel Processing With Completable Future

DZone 's Guide to

Java 8 Parallel Processing With Completable Future

Check out this full-length tutorial on how to take advantage of parallel processing in Java with futures and allOf, join, etc. methods.

· Java Zone ·
Free Resource

Everyday we see the programming use cases which should handle data-parallel to improve the performance. In Java 8, with CompletableFuture we can achieve parallel programming much simpler and readable way with methods like allOf, join, etc.. 

Whenever we call any method, we have to decide whether we need any return value from that method or not. If we don't want any return value, we can just call that method and leave the control to it.In CompletableFuture we have 2 methods which addresses the above cases:

  • CompletableFuture.supplyAsync — In case if you want the return value.
  • CompletableFuture.runAsync —  In case if you don't want the return value.

So let's take an example, we are taking 3 tasks that have to be executed parallel. 

Method 1: add -> it takes the arguments of 2 variable and returns the sum

Java


Method 2: sub-> it takes the arguments of 2 variable and returns the subtraction

Java


Method 3: mul-> it takes the arguments of 2 variable and returns the multiplication

Java


Actual CompletableFuture work starts from here. Before adding futures, we have to maintain a global list that bundles all the future list:

Java


Then, the method which we have created that has to be run parallel has to be declared as a CompletableFuture method.

Java


So, the above methods are converted into completable futures that can process parallel. As we said in the above line, all the futures are added to the global future list.

Java


Then, we have to write a line that keeps the agreement among all threads saying "wait until all the threads in the arguments get completed". For that, we have to use the allOf method.

Java
 







Then, we have to write a line that says, "after the completion of execution for all threads, collect all the return values from all the threads."

Java


Finally, define the future list as a completable future.

Java


All the setup has done for making the parallel processing using a completable future. To call that entire parallel method, below is the line using get()

Java


You will get all the results in a finalList variable.

To get the things more clear, I have written a for loop inside each method to process sysout multiple times to make each thread more time in that method.

After executing the program, just analyze the sysout comments and trace the control for better understanding. 

Topics:
completeable future, java, parallel processing, tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}