. . .
Code Example 12-4 is the code that updates the salary of Bil's friends. The delay is inside the
critical section; thus, while one thread is sleeping here, all the other threads must wait outside.
Moving the delay outside would vastly increase the performance of the program. It wouldn't be
terribly realistic to do so. As the delay represents a write to disk or some other operation on the
salary, it really must be inside the critical section.
Example 12-4 : giveRaise() (
public synchronized void giveRaise() {
Note that we release the RWlock as soon as we obtain the salary lock, allowing liquidator threads
to begin their searches. The liquidator threads are allowed to run while we're updating the salary!
To make this work correctly, the function liquidatePerson() must also lock the salary lock
before it changes anything in the object (Code Example 12-5). Also notice how we are mixing our
RWlocks with Java's synchronized sections.
Example 12-5 Removing an Element from the List (
public synchronized void liquidate() {
next =;
Global RWLock with Local Mutex to Protect Salaries
Version three of the program (Figure 12-7) uses a readers/writer lock to protect the list and a local
mutex to protect individual salaries. This way, any number of threads can run down the list
searching for people to give raises to at the same time. Once found, we need to protect the
individual salary data while we update it. Now we have overcome the major bottleneck of this
program. Many threads may now update different salaries at the same time.
Figure 12-7. Friends/Enemies: Global RWlock and Local Salary Lock
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks