问题描述
利用TDD驱出线程安全代码的好方法是什么?例如,假设我有一个工厂方法,该方法利用惰性初始化仅创建一个类的实例,然后将其返回:
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;
}
现在,我想以良好的TDD方式编写一个测试,以强制我使此代码成为线程安全的.具体来说,当两个线程同时调用此方法时,我不想创建两个实例并丢弃一个实例.这很容易做到,但是我怎么写一个让我做的测试呢?
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?
我在用Java问这个问题,但是答案应该更广泛地适用.
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.
这篇关于使用TDD驱除线程安全代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!