img
. .
thread getting in there fast enough to get the mutex is quite low. Using a FIFO mutex in this code
would make it much fairer. And slightly slower.
Example 12-3 Giving Friends Raises (from FriendThread.java)
public void run() {
while (friends != null) {
synchronized(test.people) {
Person p = Person.findPerson(friends, test.people);
if (p != null) {
p.next.giveRaise();
}
friends = friends.next;
}
Thread.yield();// If running Green Threads
}
}
Global RWLock with Global Mutex to Protect Salaries
Version two of the program uses a readers/writer lock to protect the list and a mutex to protect the
salaries. This way, any number of threads can run down the list, at the same time searching for
people to receive raises. Once found, we need to protect the salary data while we update it. We
add the SalaryLock for this purpose. Clearly, we could not update the salary if we only held a
read lock. When a thread wishes to remove one of Dan's enemies from the list, that thread must
hold a writer lock while it searches down the list and removes the offending element (see Figure
12-6).
Figure 12-6. Friends/Enemies: Global RWlock and Salary Lock
It's important for us to think very carefully about what each lock is protecting. The RWlock
protects the list structures and the pointers. It does not protect the salaries. Surprisingly, the
performance of this code is not much better than that of the previous code! Inspecting the code
closely, you should realize that very little time is spent actually searching down the list (about 1 µs
per element). It is the contention for the salary lock when the delay is non-zero that takes all the
time.
Once again, no thread may hold a pointer to any portion of the list unless it owns one of the locks.
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home