Sunday, July 15, 2012

Concurrency Tests with JUnit

Sometimes in the life of a programmer, a concurrency test is needed to check if a given framework function doesn't break the data when used simultaneously by different threads.

JUnit provides some sense of AOP by using the @Rule annotation which allows us to modify how a given test runs. I was trying to create these kind of tests for my DTO framework (jDTO Binder) and inspired by this blog post, I created a test rule that allows the programmer to specify the number of threads to run a given test case and collect some little statistics about the running time of the test.

First of all I created an implementation of TestRule.


The previous gist may be used by anyone who would like to create concurrency tests and dont care that much about the execution exceptions but rather the overall results of the tests.

The code does the following:

  1. Create a ThreadPoolExecutor with the size of the tests, you may use other executor implementation if you wish so.
  2. Create a CountdownLatch to make sure all the tests start almost at the same time.
  3. Create a CountdownLatch to block the test thread until all tests finish.
  4. Add all the required tasks to the executor, which will wait until all all have been scheduled.
  5. If some test fails, then a flag will be set to true.
  6. Log the execution time.
  7. Fail the test if some of the threads had an exception.
So at this point we're ready to use the rule on a simple concurrency test:


And as simple as that we have a concurrency test with some statistics on the running time.