The chapter explores how test-driven development can still work when code is no longer fully predictable, beginning with time-based behavior. A logging example shows why a hard-coded expected timestamp makes a test unreliable, then introduces a cleaner solution: abstracting system time behind a small API so production code can use real time while tests inject a fixed time source. This makes time-dependent code deterministic under test and also highlights a few practical choices, such as verifying the exact timestamp format with an additional focused test when needed.
The discussion then moves to multithreaded code, where unpredictability comes from scheduling, interleaving, and shared-state access. It explains that concurrent testing must look for both desirable behavior, such as thread-safe updates, blocking operations, background work, and thread coordination, and undesirable behavior, especially deadlocks and starvation. Because concurrency creates a much larger space of possible failures, the chapter recommends designing tests to maximize the chance of exposing race conditions, often by using controlled synchronization points, repeated runs, and carefully chosen assertions about invariants rather than relying on timing guesses.
Several concrete testing patterns are presented for common concurrent scenarios. A shared counter example demonstrates how to provoke race conditions and improve a flaky test by using barriers to align thread execution, eventually revealing the need for synchronization. Other examples show how to test that a method really blocks and can be interrupted, how to observe that a server starts and stops background threads, and how to wait for asynchronous results more reliably using polling or futures instead of arbitrary sleeps. The chapter concludes by surveying the main synchronization tools in Java’s concurrency library—semaphores, latches, barriers, exchangers, and futures—emphasizing that these abstractions both simplify concurrent programming and make it more testable.
Listing 7.2. Test for verifying that SystemTime obtains real time
Listing 7.4. Test for verifying that SystemTime uses the configured TimeSource
Listing 7.5. The configurable SystemTime implementation
Listing 7.6. HTTP request log-formatter test using faked system time
Listing 7.7. HTTP request log formatter implementation using SystemTime
Listing 7.10. Starting multiple threads to increment the counter
Listing 7.11. Improved version of our thread-safety test
Listing 7.12. The custom Thread class for synchronized execution
Listing 7.13. Testing for a method blocking and interrupting properly
Listing 7.15. Custom Thread class offering synchronization points
Listing 7.16. Test to verify that a thread is started and stopped
Listing 7.17. Test waiting for results from an asynchronous service
Listing 7.18. Retrying an assertion until it succeeds or a timeout is reached
Listing 7.19. Example usage of RetriedAssert
FAQ
Why is time-dependent functionality difficult to test in the first place?Time is inherently unpredictable from a test’s point of view because the code under test may query the system clock directly. If the test hard-codes an expected timestamp, it will likely fail because the real time keeps changing while the test runs.What is the main problem with the naïve log-formatter test shown in the chapter?The test hard-codes a timestamp in the expected log output, but the formatter is supposed to generate that timestamp from the current system time. Since the test cannot control real time, the expected and actual values will almost never match.Why not simply pass the current time as an extra parameter to every method that needs it?That would push the problem around instead of solving it. It would clutter the code base with time parameters everywhere and still leave you needing a way to obtain the real system time somewhere in the application.What is the purpose of the SystemTime abstraction?SystemTime provides a controllable wrapper around system time access. Instead of calling System.currentTimeMillis(), creating Date instances directly, or using Calendar.getInstance() everywhere, production code asks SystemTime for the current time, and tests can substitute a fake TimeSource.How does a TimeSource help make tests deterministic?A TimeSource is an interface that supplies time values. In production, it can delegate to the real system clock, while in tests it can return a fixed, known value. That makes time-based output predictable and easy to assert.Why should tests reset the configured TimeSource after they finish?Because a fake TimeSource can affect later tests if it is left in place. Resetting it during teardown prevents hidden test dependencies and keeps the rest of the test suite using the expected default system time.What is the difference between thread-safety and synchronization in concurrent tests?Thread-safety means code still behaves correctly when accessed by multiple threads at once. Synchronization is one of the mechanisms used to achieve or coordinate that correct behavior, such as controlling when threads proceed or ensuring shared data is updated safely.Why is Thread.sleep() considered a poor way to test concurrency?Because it is unreliable and slow. Sleeping does not guarantee that other threads have reached the desired point in execution, and a test may still pass or fail depending on scheduling luck rather than actual correctness.Why does the chapter recommend using barriers and latches in concurrency tests?They help coordinate threads so the test can maximize concurrency and control timing more reliably. A barrier can make threads wait until enough participants arrive, while a latch can block until a specific condition or number of events occurs.What are the main standard synchronization objects discussed in the chapter?The chapter highlights semaphores, latches, barriers, and futures. These are useful building blocks for coordinating threads, limiting access, waiting for events, and retrieving asynchronous results in a controlled way.
pro $24.99 per month
access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!