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.
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.