In a multi-threaded environment where several threads gonna executes tasks which might be not independent requires to communicate with each others, one of the common way used in java is using wait(), notify() and notifyAll().
When one of the thread is waiting for a condition to occur which resides in the condition queue requires to have get notification for the condition to occur. Other thread which is working something notify others thread that they have done their work means the condition is full filled and others can do their work. Generally programmers those who are novice to the working of notify() and notifyAll() simply calls notify() and thinks that their work is done...Hurrey.. But wait there is a technical gotcha.
There may be multiple threads waiting for the condition to occur for different condition predicate. calling notify() only wake up a single thread in the queue, the thread grabs the lock and check the condition it might happen that the condition is not for that thread, that thread again goes to the suspended state, but others thread will not be able to check for their case, and this might be a simple case of lost signal or signal hacking..
Using notifyAll() wakes all others threads which are in suspended state and hence no of threads comes to the running state, and one of the thread grabs the lock and check for their particular condition. This makes sure the correct working of your threaded program.
No comments:
Post a Comment