Search code examples
javamultithreadingtestingconcurrencycontention

reliably reproducing db contention


we experience with some regularity contention on a database table, and would like to evaluate a number of different options for resolving this issue.

in order to do so, i need to reproduce in a test case, contention on a table (any table) with repeatable reliability.

the approach i'm considering would be to reverse the semantics of a lock (e.g. java.util.concurrent.locks.ReentrantLock) and to release the lock when writing on the table begins, allowing all reads to occur at the time when the writing begins.

So therefore one writer thread holds the lock until shortly before doing an insert to a table, and then releasing the lock, multiple reader threads would attempt to run select statements against the same table.

Was wondering if there were any thoughts on such an approach, or if there is a simpler approach that could, with 100% reliability, reproduce contention on a db table.

thanks


Solution

  • You could use a CountDownLatch with a count of 1.

    final CountDownLatch barrier = new CountDownLatch(1);
    

    You launch all of the reader threads, whose first action is

    barrier.await();
    

    then the writer thread can

    barrier.countDown();
    

    at which point all of the readers will merrily fire away.