Java Reference
In-Depth Information
as exhibiting poor concurrency : the number of simultaneous invocations is limited not by
the availability of processing resources, but by the structure of the application itself. For-
tunately, it is easy to improve the concurrency of the servlet while maintaining thread safety
by narrowing the scope of the synchronized block. You should be careful not to make the
scope of the synchronized block too small; you would not want to divide an operation
that should be atomic into more than one synchronized block. But it is reasonable to try
to exclude from synchronized blocks long-running operations that do not affect shared
state, so that other threads are not prevented from accessing the shared state while the long-
running operation is in progress.
CachedFactorizer in Listing 2.8 restructures the servlet to use two separate syn-
chronized blocks, each limited to a short section of code. One guards the check-then-act
sequence that tests whether we can just return the cached result, and the other guards up-
dating both the cached number and the cached factors. As a bonus, we've reintroduced the
hit counter and added a “cache hit” counter as well, updating them within the initial syn-
chronized block. Because these counters constitute shared mutable state as well, we must
use synchronization everywhere they are accessed. The portions of code that are outside the
synchronized blocks operate exclusively on local (stack-based) variables, which are not
shared across threads and therefore do not require synchronization.
Listing 2.8. Servlet that Caches its Last Request and Result.
Search WWH ::




Custom Search