Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using TDD to drive out thread-safe code

What's a good way to leverage TDD to drive out thread-safe code? For example, say I have a factory method that utilizes lazy initialization to create only one instance of a class, and return it thereafter:

private TextLineEncoder textLineEncoder;
...
public ProtocolEncoder getEncoder() throws Exception {
    if(textLineEncoder == null)
        textLineEncoder = new TextLineEncoder();
    return textLineEncoder;
}

Now, I want to write a test in good TDD fashion that forces me to make this code thread-safe. Specifically, when two threads call this method at the same time, I don't want to create two instances and discard one. This is easily done, but how can I write a test that makes me do it?

I'm asking this in Java, but the answer should be more broadly applicable.

like image 438
Don Branson Avatar asked Feb 11 '09 14:02

Don Branson


2 Answers

You could inject a "provider" (a really simple factory) that is responsible for just this line:

 textLineEncoder = new TextLineEncoder();

Then your test would inject a really slow implementation of the provider. That way the two threads in the test could more easily collide. You could go as far as have the first thread wait on a Semaphore that would be released by the second thread. Then success of the test would ensure that the waiting thread times out. By giving the first thread a head-start you can make sure that it's waiting before the second one releases.

like image 84
James A Wilson Avatar answered Sep 18 '22 12:09

James A Wilson


It's hard, though possible - possibly harder than it's worth. Known solutions involve instrumenting the code under test. The discussion here, "Extreme Programming Challenge Fourteen" is worth sifting through.

like image 43
Morendil Avatar answered Sep 18 '22 12:09

Morendil