DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Efficient Asynchronous Processing Using CyclicBarrier and CompletableFuture in Java
  • Advanced Brain-Computer Interfaces With Java
  • Distributed Computing Simplified
  • Optimizing Java Applications: Parallel Processing and Result Aggregation Techniques

Trending

  • Leveraging Apache Flink Dashboard for Real-Time Data Processing in AWS Apache Flink Managed Service
  • From APIs to Actions: Rethinking Back-End Design for Agents
  • Tactical Domain-Driven Design: Bringing Strategy to Code
  • Microservices: Externalized Configuration
  1. DZone
  2. Coding
  3. Java
  4. Java 8 Parallel Processing With Completable Future

Java 8 Parallel Processing With Completable Future

By 
Naveen Yalla user avatar
Naveen Yalla
·
Jul. 06, 20 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
52.4K Views

Join the DZone community and get the full member experience.

Join For Free

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
xxxxxxxxxx
1
 
1
 public static  Integer  addFun1(int a, int b) {
2
        System.out.println(Thread.currentThread().getName());
3
        for (int i=0;i<10;i++){
4
            System.out.print(Thread.currentThread().getName()+i);
5
        }
6
        return  a+b ;
7
    }


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

Java
xxxxxxxxxx
1
 
1
 public static  Integer  subFun1(int a, int b) {
2
        System.out.println(Thread.currentThread().getName());
3
        for (int i=0;i<10;i++){
4
            System.out.print(Thread.currentThread().getName()+i);
5
        }
6
        return  a-b ;
7
    }


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

Java
xxxxxxxxxx
1
11
9
 
1
 public static  Integer  mulFun1(int a, int b) {
2
        System.out.println(Thread.currentThread().getName());
3
        for (int i=0;i<10;i++){
4
            System.out.print(Thread.currentThread().getName()+i);
5
        }
6
        return  a*b ;
7
    }


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

Java
xxxxxxxxxx
1
 
1
List<CompletableFuture<Integer>> futuresList = new ArrayList<CompletableFuture<Integer>>();


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

Java
xxxxxxxxxx
1
 
1
 CompletableFuture<Integer> addAsy = CompletableFuture.supplyAsync(()->(addFun1(10,5)));
2
CompletableFuture<Integer> subAsy = CompletableFuture.supplyAsync(()->(subFun1(10,5)));
3
CompletableFuture<Integer> mulAsy = CompletableFuture.supplyAsync(()->(mulFun1(10,5)));


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
xxxxxxxxxx
1
 
1
futuresList.add(addAsy);
2
futuresList.add(subAsy);
3
futuresList.add(mulAsy);


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
 




xxxxxxxxxx
1


 
1
CompletableFuture<Void> allFutures = CompletableFuture
2
                .allOf(futuresList.toArray(new CompletableFuture[futuresList.size()]));



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
xxxxxxxxxx
1
 
1
CompletableFuture<List<Integer>> allCompletableFuture = allFutures.thenApply(future -> {
2
            return futuresList.stream().map(completableFuture -> completableFuture.join())
3
                    .collect(Collectors.toList());
4
        });


Finally, define the future list as a completable future.

Java
xxxxxxxxxx
1
 
1
CompletableFuture<List<Integer>> completableFuture = allCompletableFuture.toCompletableFuture();


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
xxxxxxxxxx
1
 
1
 try {
2
            List<Integer> finalList = (List<Integer>) completableFuture.get();
3
            System.out.print(finalList);
4
        } catch (InterruptedException e) {
5
            e.printStackTrace();
6
        } catch (ExecutionException e) {
7
            e.printStackTrace();
8
        }


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. 

Java (programming language) Processing

Opinions expressed by DZone contributors are their own.

Related

  • Efficient Asynchronous Processing Using CyclicBarrier and CompletableFuture in Java
  • Advanced Brain-Computer Interfaces With Java
  • Distributed Computing Simplified
  • Optimizing Java Applications: Parallel Processing and Result Aggregation Techniques

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook