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

  • Advanced Brain-Computer Interfaces With Java
  • Distributed Computing Simplified
  • Optimizing Java Applications: Parallel Processing and Result Aggregation Techniques
  • Speeding Up Large Collections Processing in Java

Trending

  • Creating a Web Project: Caching for Performance Optimization
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 2
  • Modern Test Automation With AI (LLM) and Playwright MCP
  • Understanding the Shift: Why Companies Are Migrating From MongoDB to Aerospike Database?
  1. DZone
  2. Coding
  3. Java
  4. Efficient Asynchronous Processing Using CyclicBarrier and CompletableFuture in Java

Efficient Asynchronous Processing Using CyclicBarrier and CompletableFuture in Java

Learn how JAVA concurrency features such as CyclicBarrier and CompletableFuture can be used together to achieve efficiency.

By 
Sulakshana Singh user avatar
Sulakshana Singh
·
Jan. 03, 25 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
7.1K Views

Join the DZone community and get the full member experience.

Join For Free

In today’s world enterprise applications increasingly require the ability to asynchronously process large datasets. The processing of data must correlate and compute results at the same time. This article illustrates how CyclicBarrier and CompletableFuture, combined, perform efficiently in processing and producing desired results from large datasets.

Why to Use Asynchronous Processing?

Asynchronous processing lets tasks run without blocking others. Unlike synchronous processing, which runs tasks in order, it allows multiple tasks to proceed at once. This method is handy for tasks that need to wait for external resources, like network requests. It boosts efficiency and responsiveness in applications. 

In this article, Asynchronous processing of a given dataset is ensured using the following features:

  1. CyclicBarrier: A synchronizer that allows a set of threads to wait for each other to reach the same barrier point before continuing, which means no thread can pass beyond a point (the barrier) unless all threads are at the same barrier.
  2. CompletableFuture: Java provides a multifaceted class that helps in asynchronous computation. It is a powerful tool for nonblocking computation, enhancing the performance of applications. In our scenario, it allows us to run a parallel average salary calculation for each department.

Problem Statement

Let's consider that there is a comma-separated file (CSV) that contains a list of employees, their departments, and their salaries. The objective is to find the average salary for each department using asynchronous execution; in other words, execute code in parallel and reduce execution time.

The dataset shown below is available at the GitHub location.

Dataset


Solution Approach

The solution is split into the following steps:

  1. Read CSV file and parse employee data: The OpenCV library is used to read and parse the CSV file into a list of Employee Java objects.
  2. Group employees by department: Using Java’s Collectors.groupingBy, we will group employees by their department.
  3. Calculate average salaries asynchronously: Using CompletableFuture, the average salary for each department is calculated concurrently.
  4. Synchronize the results: With CyclicBarrier, it is ensured that all the department calculations are completed before the results are generated.

The code snippet is as follows:

Code snippet


Explanation of Code

  1. Data loading: The opencsv library is used to parse the employees.csv file into a list of employees. This allows us to easily work with employee data in our code.
  2. Grouping by department: The employees are grouped by their department field using the static factory method Collectors.groupingBy() [made available since Java8] allows the processing of collections of data in a declarative way.
  3. Asynchronous execution: Each department's salary calculation is done asynchronously using CompletableFuture.runAsync. This ensures that the calculations are done in parallel, leveraging available CPU resources efficiently.
  4. Synchronization with CyclicBarrier: The CyclicBarrier ensures that all department calculations are completed before generating the end results. The barrier.await() method makes sure each thread waits for the others to reach this point before proceeding.
  5. Calculating and storing averages: The calculateAndStoreAverage method computes the average salary for each department and stores it in a ConcurrentHashMap for thread-safe access.
  6. Result: After all threads have completed, the average salary for each department is printed to the console as below.

The average salary for each department is printed to this console

Conclusion

Asynchronous Programming

CompletableFuture allows the execution of tasks concurrently, making it possible to calculate department averages in parallel.

Efficient Synchronization

The CyclicBarrier ensures that the program waits until all departments have completed their average salary calculations.

Java Concurrency

This is a simple and efficient concurrency solution by combining CompletableFuture and CyclicBarrier, which makes this approach perfect for multiple independent tasks that need to be run in parallel.

It is quite an efficient and scalable way to expand and manage a high number of departments or employee records without any major change in core logic. Therefore, following these asynchronous programming patterns, Java developers can now develop high-performance applications that process data in parallel within a single thread.

The full code snippet is available in my GitHub repository.

References

The article is based on various official resources. The official JAVA SE 17 documentations for CyclicBarrier and CompletableFuture are very insightful regarding functionality and their implementation. 

Baeldung's guide on CyclicBarrier offers practical examples and use cases to show how to use cyclicBarrier for concurrent programming. Together, these references provide the background for the ideas and examples given in this article.

Java (programming language) Processing

Opinions expressed by DZone contributors are their own.

Related

  • Advanced Brain-Computer Interfaces With Java
  • Distributed Computing Simplified
  • Optimizing Java Applications: Parallel Processing and Result Aggregation Techniques
  • Speeding Up Large Collections Processing in Java

Partner Resources

×

Comments

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: