Even for unlocking, notify() should suffice in stead of notifyAll() since only one other thread/client will be able to get the lock. So, you're actually slowing the system if you wake up all the threads.
Missing something again?
Using notify() only:
I started up 30 threads that all tried to loop through the same 3 recs and modify them, and it works perfectly every time.
The elementary puzzler I was considering today, is why is notify() sufficient in this context instead of notifyAll()?
while (obtained) wait();
//it is unclear why an "if (obtained)" would not work just
//just as well as long as the thread scheduler is operating
//100% correctly. Does anyone know the answer to this?
Or, even if ThreadC were made running first, the thread
scheduler still knows that it "owes" a notify to one of
those threads that are waiting due to having specifically
Originally posted by Jacques Bosch:
Concerning this, here's a question not commented on yet:
Just to expand on Marlene's point "If several threads were waiting on different conditions (not your example), it would not suffice to use notify" ...
* Thread A locks record 1
* Thread B locks record 2
* Thread C attempts to lock record 1 - goes into wait
* Thread D attempts to lock record 2 - goes into wait
* Thread A unlocks record 1 - calls notify()
* Thread D wakes up, checks record 2 is still locked, goes back into wait
You now have threads waiting unnecessarily. If you had called notifyAll() then this would not have occured.
Since notifyAll() put all waiting threads into the ready-to-run state, they will be able to run as soon as the scheduler gives them a chance. So even though Thread D "woke up" first (was scheduled first) as soon as it has gone back into wait state the scheduler will look for other threads that are ready-to-run and will schedule one of them. So thread C managed to lock its record.
Question: would I be correct in asserting that for my original example, notify() would be sufficient and equal to notifyAll()?
You have one class, this, being used as the monitor against three different lock flags: boolean variables a, b, and c.
Question: does this particular mutex have a particular name?
Now, let us return back to the notify() case in your example. I find it interesting
that the process even is guaranteed to come to completion! That is,
I intuitively wonder if it was only luck that when notify() was used,
all threads eventually got the lock on their particular boolean and then
subsequently released it.
Question: Of course, your comment, "And that is completely variable -
you cannot accurately predict how long it will take to complete." may
be another way of saying: the darned thing may never complete when
you use notify().