Tuesday 20 March 2012

Using Spin Locks to simplify unit testing of async code

A common barrier to working with concurrent code is having confidence in it. It can be difficult to unit test. The most common solution is to generate events that the unit test can hook in to. However that adds complexity and sometimes it is either too difficult, muddy or just not desirable. In those cases a simpler tool is the good old spin lock. Below is a Scala wrapper around the JUnit assertEquals method that keeps retrying a condition until it is true. If that condition is not true within n milliseconds then the test fails. Simple, but effective.
  def assertEqualsWithRetry[T]( expected:T, actual: => T, maxDurationMillis:Int=5000 ) {
    val startMillis    = System.currentTimeMillis()
    def durationMillis = System.currentTimeMillis() - startMillis

    while ( durationMillis < maxDurationMillis && expected != actual ) {
      Thread.`yield`()
    }

    assertEquals( expected, actual )
  }

No comments:

Post a Comment