How Do You Test Thread Safety?

I'm all about testing.  I do my best to adhere to test-driven development (though, admittedly, sometimes that's hard when you're doing some experimental work just to see if something's possible).  I even go as far as mocking full page request lifecycles to test controls and page behavior.

But say you have a little code block like this:

if(!initialized)
{
  lock(syncroot)
  {
    if(!initialized)
    {
      Initialize();
    }
  }
}

Standard lock/double-check stuff to ensure things only get initialized once.  Does anyone have a good way to test that?  A quick search of the net turns up... well, pretty much nothing.

posted on Thursday, August 30, 2007 8:54 AM | Filed Under [ GeekSpeak .NET ]

Comments

Gravatar # re: How Do You Test Thread Safety?
by Chris Bilson at 8/30/2007 7:22 PM
In your example, you could lock syncroot yourself, spin up a worker thread, let the SUT run to the first lock, set initialized to true/false, let go of the lock, then verify that Initialize got called or not as appropriate.

That looks like the only logic to test in this method.

What I would be worried about is Initialize() and initialized: making sure Initialize() doesn't re-enter the above block, and initialized is never touched without a lock. That's the hard part to test, I think.
Gravatar # re: How Do You Test Thread Safety?
by Lars Thorup at 9/14/2007 1:01 PM
Take a look at my recent article Test Driven Thread Safety.
Comments have been closed on this topic.