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

  • Comparison of Various AI Code Generation Tools
  • Database Integration Tests With Spring Boot and Testcontainers
  • 7 Awesome Libraries for Java Unit and Integration Testing
  • IntelliJ Integration for Mockito

Trending

  • Is Agile Right for Every Project? When To Use It and When To Avoid It
  • Automatic Code Transformation With OpenRewrite
  • Automating Data Pipelines: Generating PySpark and SQL Jobs With LLMs in Cloudera
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Five Ways of Synchronising Multithreaded Integration Tests

Five Ways of Synchronising Multithreaded Integration Tests

By 
Roger Hughes user avatar
Roger Hughes
·
Oct. 11, 22 · Interview
Likes (1)
Comment
Save
Tweet
Share
9.4K Views

Join the DZone community and get the full member experience.

Join For Free

A few weeks ago I wrote a blog on synchronizing multithreaded integration tests, which was republished on DZone Javalobby from where it received a comment from Robert Saulnier who quite rightly pointed out that you can also use join() to synchronize a worker thread and its unit tests. This got me thinking, just how many ways can you synchronise multi-threaded integration tests? So, I started counting... and came up with:

  1. Using a random delay.
  2. Adding a CountDownLatch
  3. Thread.join()
  4. Acquiring a Semaphore
  5. With a Future and ExecutorService


Now, I’m not going to explain all the following in great detail, I’ll let the code speak for itself, except to say that all the code samples do roughly the same thing: the unit test creates a ThreadWrapper instance and then calls its doWork() method (or call() in the case of the Future). The unit test’s main thread then waits for the worker thread to complete before asserting that the test has passed.


For the sample code demonstrating points 1 and 2 take a look at my original blog on Synchronizing Multithreaded Integration Tests, though I wouldn’t recommend point 1: using a random delay.



Thread.join()


public class ThreadWrapper {



   private Thread thread;



   /**

   * Start the thread running so that it does some work.

   */

   public void doWork() {



   thread = new Thread() {



   /**

   * Run method adding data to a fictitious database

   */

   @Override

   public void run() {



   System.out.println("Start of the thread");

   addDataToDB();

   System.out.println("End of the thread method");

   }



   private void addDataToDB() {



   try {

   Thread.sleep(4000);

   } catch (InterruptedException e) {

   e.printStackTrace();

   }

   }

   };



   thread.start();

   System.out.println("Off and running...");

   }



   /**

   * Synchronization method.

   */

   public void join() {



   try {

   thread.join();

   } catch (InterruptedException ex) {

   Thread.currentThread().interrupt();

   }

   }

 }



public class ThreadWrapperTest {



   @Test

   public void testDoWork() throws InterruptedException {



   ThreadWrapper instance = new ThreadWrapper();



   instance.doWork();

   instance.join();



   boolean result = getResultFromDatabase();

   assertTrue(result);

   }



   /**

   * Dummy database method - just return true

   */

   private boolean getResultFromDatabase() {

   return true;

   }

 }



Acquiring a Semaphore


public class ThreadWrapper {



   /**

   * Start the thread running so that it does some work.

   */

   public void doWork() {

   doWork(null);

   }



   @VisibleForTesting

   void doWork(final Semaphore semaphore) {



   Thread thread = new Thread() {



   /**

   * Run method adding data to a fictitious database

   */

   @Override

   public void run() {



   System.out.println("Start of the thread");

   addDataToDB();

   System.out.println("End of the thread method");

   semaphore.release();

   }



   private void addDataToDB() {



   try {

   Thread.sleep(4000);

   } catch (InterruptedException e) {

   e.printStackTrace();

   }

   }

   };



   aquire(semaphore);

   thread.start();

   System.out.println("Off and running...");

   }



   private void aquire(Semaphore semaphore) {

   try {

   semaphore.acquire();

   } catch (InterruptedException e) {

   e.printStackTrace();

   }

   }

 }



public class ThreadWrapperTest {



   @Test

   public void testDoWork() throws InterruptedException {



   ThreadWrapper instance = new ThreadWrapper();



   Semaphore semaphore = new Semaphore(1);

   instance.doWork(semaphore);

   semaphore.acquire();



   boolean result = getResultFromDatabase();

   assertTrue(result);

   }



   /**

   * Dummy database method - just return true

   */

   private boolean getResultFromDatabase() {

   return true;

   }

 }



With a Future


public class ThreadWrapper implements Callable<Boolean> {



   @Override

   public Boolean call() throws Exception {

   System.out.println("Start of the thread");

   Boolean added = addDataToDB();

   System.out.println("End of the thread method");

   return added;

   }



   /**

   * Add to the DB and return true if added okay

   */

   private Boolean addDataToDB() {



   try {

   Thread.sleep(4000);

   } catch (InterruptedException e) {

   e.printStackTrace();

   }

   return Boolean.valueOf(true);

   }

 }



public class ThreadWrapperTest {



   @Test

   public void testCall() throws ExecutionException, InterruptedException {



   ThreadWrapper instance = new ThreadWrapper();



   ExecutorService executorService = Executors.newFixedThreadPool(1);



   Future<Boolean> future = executorService.submit(instance);



   Boolean result = future.get();



   assertTrue(result);

   }

 }


Having listed all these methods, the next thing to consider is which one is the best? In asking that question you have to define the word “best” in terms of best for what? Best for simplicity? Maintainability? Speed or code size? After all Programming the Art of Making the Right Decision. You may have guessed that I don’t like the random delay idea and prefer the use of a CountDownLatch. Thread.join() is a bit old school; remember that the likes of Semaphore and CountDownLatch were written to improve on the original Java threading techniques. ExecutorService seems a little heavy weight for what we need here. At the end of the day the choice of technique really comes down to personal preference.


Finally, I’ve listed five ways of synchronizing multi-threaded integration tests; however, if you can think of any others please let me know...



The source code for this blog is available on Github.

unit test Integration

Published at DZone with permission of Roger Hughes, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Comparison of Various AI Code Generation Tools
  • Database Integration Tests With Spring Boot and Testcontainers
  • 7 Awesome Libraries for Java Unit and Integration Testing
  • IntelliJ Integration for Mockito

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!