We use wait(), notify(), or notifyAll() method
mostly for inter-thread communication in Java.
One thread is waiting after checking a
condition .Calling notify() or notifyAll() methods issues a notification to a
single or multiple thread that a condition has changed and now all the threads
which are waiting, fight for object lock on which they are waiting and lucky
thread returns from wait() method after reacquiring the lock and proceed
further.
which could lead to potential race condition
and now how to resolved it? This race
condition is resolved by using synchronized keyword and locking provided by
Java. In order to call the wait (), notify () or notifyAll () methods in Java,
we must have obtained the lock for the object on which we're calling the
method.
Since the wait() method in Java also releases
the lock prior to waiting and reacquires the lock prior to returning from the
wait() method, we must use this lock to ensure that checking the condition and setting the condition is atomic which can
be achieved by using synchronized method or block in Java.
No comments:
Post a Comment