Bert's Blog

Dec 4

Thwarting Threading

It’s difficult to test concurrent behaviour, because there’s an arbitrary delay between calling start() on a thread and when it executes. That is unless you’ve discovered the CyclicBarrier.

I’ve lost count of the number of bottlenecks and race conditions I’ve unearthed with this snippet.

  long timeMe(int threads) throws Exception {
    final CyclicBarrier start = 
      new CyclicBarrier(threads+1);
    final CyclicBarrier end = 
      new CyclicBarrier(threads+1);
    for(int i=0; i < threads; i++){
      new Thread(){
        public void run() {
          try{   
            start.await();
            // insert suspect code here
            end.await();
          } catch(Exception e) {}
        }
      }.start();
    }
    start.await();
    long time = System.currentTimeMillis();
    end.await();
    return System.currentTimeMillis()-time;
  } 

A CyclicBarrier blocks when await() is called. When the specified number of threads calling await() is reached, the threads are released simultaneously. Perfect for load testing or saturating a network!