Why are while-loop wait conditions safe in multithreaded context?
I am having a hard time understanding how this works:
while(<some condition>){
wait();
}
OR this example:
while(<some condition>){
condition.await();
}
When the thread has already passed <some condition>
, it may happen that it is <some condition>
already false
running wait()
or await()
.
So that wait()
or await()
can be called with an already invalid condition - this means that the intent is violated.
What's wrong with my logic?
source to share
From the docs for wait()
:
The current thread must own this object monitor. ... This thread releases the owner of this monitor and waits until another thread tells the threads waiting on this object monitor to wake up, either through a call to the notification method or the notifyAll method. The thread then waits until it can re-acquire ownership of the monitor and resume execution.
(emphasis mine)
In other words, without the block, synchronized
your code will issue IllegalMonitorStateException
. C synchronized
, on the other hand, your state will be checked atomically with a call wait();
.
This does not automatically mean that you are not in trouble, because it is "atomically" here only with respect to the object you are syncing (in your case this
) and only with respect to other synchronized access to that object. If your state depends on different objects, or you refer to an object without synchronization elsewhere, things can go wrong. So, don't do it.
The same arguments concerning the use Lock
and Condition
s. See this sample code. Condition variables are derived from blocking objects, and synchronized
/ wait
/ is notify
similar Lock
;. unlock
/ await
/signal
source to share