Multithreading – use TDD to drive thread safe code

What is a good way to use TDD to launch thread safe code? For example, suppose I have a factory method that uses deferred initialization to create an instance of a class, and then returns:

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

Now, I want to write a test in a good TDD way, forcing 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 It's easy to do, but how to write a test for me?

I ask this question in Java, but the answer should apply more widely

Solution

Nevertheless, it's hard and probably worth more than it Known solutions involve code under test Here, the discussion of "extreme programming challenge four" is worth screening

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>