Java Reference
In-Depth Information
Imagine that we want to improve the performance of our servlet by caching the most recently
computed result, just in case two consecutive clients request factorization of the same num-
ber. (This is unlikely to be an effective caching strategy; we offer a better one in Section 5.6 . )
To implement this strategy, we need to remember two things: the last number factored, and
its factors.
We used AtomicLong to manage the counter state in a thread-safe manner; could we per-
haps use its cousin, AtomicReference , [6] to manage the last number and its factors? An
attempt at this is shown in UnsafeCachingFactorizer in Listing 2.5 .
Listing 2.5. Servlet that Attempts to Cache its Last Result without Adequate Atomicity. Don't do this.
Unfortunately, this approach does not work. Even though the atomic references are individu-
ally thread-safe, UnsafeCachingFactorizer has race conditions that could make it
produce the wrong answer.
Search WWH ::




Custom Search