Core Concepts for Test-Driving Threads

In this chapter, you’ll work through an example that demonstrates a few core concepts around test-driving threads.

Separate threading logic from application logic. The best object-oriented design is one that separates concerns as much as possible. Your design for a multithreaded application should be no different. Threading is one concern, and your application logic is another. Keep them separate as much as possible and minimize their intermingling. Once again, small methods and classes are a best friend here (see Benefits of Small Methods).

Sleep is bad, m’kay? Pausing execution in a thread via sleep_for, in order to wait for a condition to be met, is a poor solution for many reasons. Test runs will be slow and failures sporadic. Often the reaction to a failing “sleeper” test is to increase the wait time, which will increase the average test execution time and, worse, hide any real problems longer.

Throttle down to single-threaded for application-specific tests. Your application code must first work in a single-threaded environment before you introduce threads. Once the threads are in place, you’ll still need to demonstrate that the application code performs correctly.

Providing a way to eliminate concurrency concerns for the application-specific unit tests will help you keep your sanity. In a sense, testing multithreaded code moves you into the realm of integration testing. To override threading control, you can either design hooks into your application or introduce test doubles.

Demonstrate concurrency issues before introducing concurrency controls. Throwing concurrency controls (locks and waits) everywhere can severely degrade your application’s performance and might not even solve any real concurrency problems. The core theme of the following example involves first writing a test that demonstrates a potential concurrency problem and then exacerbating it to the point where the test fails every time. Demonstrating failure first allows you to remain test-driven. You add only the concurrency control that makes the test pass.

The challenge of test-driving threads still requires careful thought and analysis around how the threads can interleave. Following the previous concepts may minimize the troubles you face and should result in a cleaner solution.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.239.44