Example: Injecting Synchronization through Logging
Although I quite melodramatically warned against exploiting logging frameworks for testing, some race conditions require their use. Let’s look at a real-life example I encountered.
Consider the code in Listing 13-11. At first blush, it may appear that this code is thread-safe. Java guarantees that the individual operations of the Vector
class are thread-safe. The retrieval of the first element and its removal are in a synchronized
block. However, small though it may be, the time between the test for whether logRecords
is empty in the while
condition and the synchronized
block in which that test is acted on represents a classic check-and-modify race condition. When this method in invoked in high ...
Get Quality Code: Software Testing Principles, Practices, and Patterns now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.