Java Reference
In-Depth Information
Listing 11.5. Reducing Lock Duration.
Reducing the scope of the lock in
userLocationMatches
substantially reduces the num-
ber of instructions that are executed with the lock held. By Amdahl's law, this removes an
impediment to scalability because the amount of serialized code is reduced.
Because
AttributeStore
has only one state variable,
attributes
, we can improve
it further by the technique of
delegating thread safety
(
Section 4.3
). By replacing
at-
tributes
with a thread-safe
Map
(a
Hashtable
,
synchronizedMap
, or
Concur-
rentHashMap
),
AttributeStore
can delegate all its thread safety obligations to the
underlying thread-safe collection. This eliminates the need for explicit synchronization in
AttributeStore
, reduces the lock scope to the duration of the
Map
access, and removes
the risk that a future maintainer will undermine thread safety by forgetting to acquire the ap-
propriate lock before accessing
attributes
.
While shrinking
synchronized
blocks can improve scalability, a
synchronized
block
can be
too
small—operations that need to be atomic (such updating multiple variables that
participate in an invariant) must be contained in a single
synchronized
block. And be-
cause the cost of synchronization is nonzero, breaking one
synchronized
block into mul-
tiple
synchronized
blocks (correctness permitting) at some point becomes counterpro-