Java Reference
In-Depth Information
Reduce the frequency with which locks are requested; or
Replace exclusive locks with coordination mechanisms that permit greater concur-
rency.
11.4.1. Narrowing Lock Scope (“Get in, Get Out”)
An effective way to reduce the likelihood of contention is to hold locks as briefly as possible.
This can be done by moving code that doesn't require the lock out of synchronized
blocks, especially for expensive operations and potentially blocking operations such as I/O.
It is easy to see how holding a “hot” lock for too long can limit scalability; we saw an ex-
ample of this in SynchronizedFactorizer in Chapter 2 . If an operation holds a lock
for 2 milliseconds and every operation requires that lock, throughput can be no greater than
500 operations per second, no matter how many processors are available. Reducing the time
the lock is held to 1 millisecond improves the lock-induced throughput limit to 1000 opera-
tions per second. [8]
AttributeStore in Listing 11.4 shows an example of holding a lock longer than neces-
sary. The userLocationMatches method looks up the user's location in a Map and uses
regular expression matching to see if the resulting value matches the supplied pattern. The
entire userLocationMatches method is synchronized , but the only portion of the
code that actually needs the lock is the call to Map.get .
Listing 11.4. Holding a lock longer than necessary.
Search WWH ::




Custom Search