I know that this is a repeated question. But I am unable to understand by the explanation. I want to understand it cleraly with a well example. Can any one please help.
"Why we call wait(), notify() methods from a synchronized context".
I know that this is a repeated question. But I am unable to understand by the explanation. I want to understand it cleraly with a well example. Can any one please help.
"Why we call wait(), notify() methods from a synchronized context".
We use wait () and notify () or notifyAll () method mostly for inter-thread communication.
One thread is waiting after checking a condition e.g. In Producer Consumer example Producer Thread is waiting if buffer is full and Consumer thread notify Producer thread after he creates a space in buffer by consuming an element. calling notify() or notifyAll() issues a notification to a single or multiple thread that a condition has changed and once notification thread leaves synchronized block , 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. Let’s divide this whole operation in steps to see a possibility of race condition between wait () and notify () method in Java, we will use Produce Consumer thread example to understand the scenario better:
So due to race condition here we potential lost a notification and if we use buffer or just one element Produce thread will be waiting forever and your program will hang. In conclusion in order to avoid the race condition, wait(), notify() and notifyAll() is called from a synchronized context.
HTH.
when we use synchronize in threads, it means we do make a lock on that object and that object can be used only by one thread at one time to avoid various kinds of concurrency issues.
wait() and notify() methods are used only from synchronized context.
wait method pauses the working of current thread and releases the lock it is holding on any object so that other threads can use that synchronized object.
when other thread is done with its work then it calls the notify method which causes the first thread to again obtain the lock on the object and resume its working.
you can easily get examples from net.