Inter Thread Communication in Java using Wait Notify Example

Selasa, 25 Februari 2014

Wait and notify methods in Java are used for inter-thread communication i.e. if one thread wants to tell something to another thread, it uses notify() and notifyAll() method of java.lang.Object. Classical example of wait and notify method is Producer Consumer design pattern, where One thread produce and put something on shared bucket, and then tell other thread that there is an item for your interest in shared object, consumer thread than pick than item and do his job, without wait() and notify(), consumer thread needs to be busy checking, even if there is no change in state of shared object. This brings an interesting point on using wait and notify mechanism, a call to notify() happens, when thread changed state of shared object i.e. in this case producer change bucket from empty to not empty, and consumer change state from non empty to empty. Also wait and notify method must be called from synchronized context, wondering why, read this link for some reasons which makes sense. Another important thing to keep in mind while calling them is, using loop to check conditions instead of if block. This is really tricky for beginners, which often don't understand difference and wonders why wait and notify get called form loops. Joshua Bloch has a very informative item on his book Effective Java, I strongly suggest reading that. In short, a waiting thread may woke up, without any change in it's waiting condition due to spurious wake up. For example, if a consumer thread, which is waiting because shared queue is empty, gets wake up due to a false alarm and try to get something from queue without further checking whether queue is empty or not than unexpected result is possible. Here is standard idiom for calling wait, notify and notifyAll methods in Java :

How to call wait method in Java :
Read more »

Related Posts by Categories

0 komentar:

Posting Komentar