Java Reference
In-Depth Information
Table 5.3 Executing parallel threads can have many different results. This shows the possible
results of executing our program with inadequate protection. While we should increment our
counter twice, we come out with a total of one.
Value
of count
Value
of temp
Thread 1
Thread 2
0
0
Integer temp = count;
0
1
temp = temp + 1
0
0
Integer temp = count;
0
1
temp = temp + 1
1
1
count = temp
1?
1
count = temp
We can protect execution from simultaneous access by adding the synchro-
nized keyword to the method:
public synchronized void count() {
For synchronized code, when a thread enters a method it locks the instance's
object so that other threads of the same instance cannot enter the method at
the same time. Here's the key: The Java synchronized keyword locks on the
object level . For Listing 5.2, a synchronized method would not have been
strong enough, because many commands could exist and write to the hash
table at the same time. Therefore, we must lock the cache object.
5.5.1
Collisions between readers can hurt performance
For cache applications, you should have far more reads from the cache than
writes to the cache. If this were not true, you'd be adding overhead without
getting much value. You don't need to protect simultaneous reads from the
cache, because reads are not destructive. However, a writer and a reader using
the cache at the same time would possibly generate unpredictable results. The
problem is that writing applications need exclusive access, so to keep the read-
ing applications out, both readers and writers must obtain a lock. Because the
locks are exclusive, readers are also reduced to sequential access. This is a clas-
sic case of the Read / Write Bottleneck antipattern.
Consider a bathroom that's located between two important rooms of a
house. It should be acceptable for many people to walk through the bath-
room, as long as no one is using it. Once someone is using the bathroom,
those passing through must clear out and the doors on either side must be
Search WWH ::




Custom Search