img
. . .
process_request(request);
}
}
The mutex protects both the list itself and the variable length. The distinction is that when the list
is empty, the consumers will go to sleep on one condition variable (consumerCV) while the
producers will go to sleep on another (producerCV) when the list is full. In this fashion the
producers can be confident that they are waking up a consumer when they put a new item on the
list, and the consumers know they are waking up a producer when they take one off. This is the
behavior we want. Let's see how we can do this in Java.
POSIX-Style Mutexes in Java
Implementing mutexes is a snap. We need an object with one boolean and two methods, lock()
and unlock(). To lock it, if the mutex is held by another thread, we wait. Otherwise, we set
owned to true (Code Example 6-19). (Later we will use a slightly more elaborate version of
mutexes which record the name of the owner, but right now we'll be simple.) To unlock, we'll just
set owned to false, then call notify() to wake up one sleeper (if any). (A slightly more
efficient version would count the sleepers.)
A sufficiently intelligent compiler could optimize this down to be identical to Pthread mutexes
with identical performance. (I do not know of any compilers sufficiently intelligent, however, and
the best code currently imaginable would be many times slower than Pthreads. A mutex class as
part of the JVM would be a very good thing.)
Code Examples 6-19 and 6-20 are simplified and should not be used. We'll show the full, working
versions of mutexes and condition variables in Actual Implementation of POSIX Synchronization.
Example 6-19 Implementing POSIX-Style Mutexes in Java
// Don't use this code, it ignores exceptions.
public class Mutex {
boolean owned = false;
public synchronized void lock() {
while (owned) {
try {
wait();
} catch (InterruptedException ie) {
// Ignore interrupts for now
}
}
owned = true;
}
public synchronized void unlock() {
owned = false;
notify();
}
}
POSIX-Style Condition Variables in Java
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home