I am learning Advanced Java & am fairly confused on this 1 topic of using the wait() & notify() methods for thread communication in concurrency programming with the sync block & sync keyword (synchronization)
I tried going through all articles I could find on the net but nothing gives a conclusive understanding as to how to use these methods on threads locking on certain objects, i have a simple code here wherein I am trying to get a thread to suspend execution for some time while another thread on the same object carries out some tasks, which when over notifies the 1st thread to resume operation. I have locked the threads on a particular object variable within my class instance & am using it as the object whose condition is to be monitored for suspending & resuming the thread.
The thread waits as intended but the notify does not work, however if I use "this" as object to monitor in general & then call the methods as
the notify method works as intended, can someone explain what I am doing wrong ?? as is why can I not set the object to monitor as the Integer variable "i" ??
any input would be much appreciated.
The Integer class is immutable. I assume that the i++ statement creates a new instance of the Integer class with the new value.
The wait, notify and synchronize statements must all refer to the same object. But the code changes what i refers to when i++ is executed.
Whenever you increment i, it will contain a new object, meaning that it is very likely that one thread is waiting on a different Integer object than the other thread is notifying.
Another problem with your code is that you're accessing a shared variable (i) in an unsynchronized way. Even if you are synchronizing on this, there are still portions of the code where you don't use synchronization at all.
You shouldn't synchronize on a mutable variable, and you also shouldn't synchronize on this. Synchronize on a private and final variable, even if you have to introduce a new variable of type Object.
Always wait in a loop that checks the waiting condition. It is not guaranteed that wait() keeps waiting until another thread calls notify(), it may wake up sooner.
Another more modern approach is to use ReentrantLock:
@Stephan van Hulst, thanks for the code & the tip, you are right actually this is a mere rough snippet, I made to understand the 2 methods so there are a lot of gaps in the sync of the objects being used by the threads.
Stephan van Hulst wrote:Another more modern approach is to use ReentrantLock
Indeed. It has an added benefit - you can have more than one condition linked to the same lock. These conditions can both have their separate await and signal calls, which can help make things clearer. For instance: