Java Reference
In-Depth Information
Wait set
Object's monitor
W
Acquire
W
Release and wait
W
R
Entry set
B
Enter
Acquire
B
B
B
Release and exit
A blocked thread
B
A running thread (owns the object's monitor)
R
A waiting thread
W
Figure 6-6. Multiple threads using an object's monitor
I will use a doctor-patients analogy while discussing threads synchronization. Suppose a doctor has a clinic to
treat patients. We know that it is very important to allow only one patient access to the doctor at a time. Otherwise,
the doctor may mix up one patient's symptoms with another patient's symptom; a patient with fever may get a
prescription for headache! Therefore, we will assume that only one patient can have access to the doctor at any
point in time. It is the same assumption that only one thread (patient) can have access to an object's monitor
(doctor) at a time.
Any patient who wants an access to the doctor must sign in and wait in the waiting room. Similarly, each object
monitor has an entry set (waiting room for newcomers) and any thread that wants to acquire the object's monitor lock
must enter the entry set first. If the patient signs in, he may get access to the doctor immediately, if the doctor is not
treating a patient and there were no patients waiting for his turn in the waiting room. Similarly, if the entry set of an
object's monitor is empty and there is no other thread that possesses the object's monitor lock, the thread entering the
entry set acquires the object's monitor lock immediately. However, if there were patients waiting in the waiting room
or one being treated by the doctor, the patient who signs in is blocked and he must wait for the doctor to become
available again. Similarly, if a thread enters the entry set, and other threads are already blocked in the entry set, or
another thread already possesses the object's monitor lock, the thread that just signed in is said to be blocked and
must wait in the entry set.
A thread entering the entry set is shown by the arrow labelled Enter. A thread itself is shown in the figure using a
circle. A circle with the text B shows a thread that is blocked in the entry set. A circle with the text R shows a thread that
has acquired the object's monitor.
What happens to the threads that are blocked in the entry set? When do they get a chance to acquire the object's
monitor? You can think about the patients blocked in the waiting room and getting their turn to be treated by the
doctor. Many factors decide which patient will be treated next. First, the patient being treated must free the doctor
before another patient can have access to the doctor. In Java, the thread that has the ownership of the object's monitor
Search WWH ::




Custom Search