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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

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

  • Unlocking AI Coding Assistants: Generate Unit Tests
  • MySQL to PostgreSQL Database Migration: A Practical Case Study
  • Understanding and Mitigating IP Spoofing Attacks
  • Enhancing Security With ZTNA in Hybrid and Multi-Cloud Deployments
  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.0K 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
Oops! Something Went Wrong

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
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!