This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I understand now that this error is caused by the updating of the object within the synchronized method.
Hold on a moment... why can't you update an object that you hold a lock to within synchronized method??
If we change the code to synchronize on example1 instead of example1.total, it works fine. But updating total is updating the state of example1 too. [After all total is an instance variable of Example1 class]
"A problem well stated is a problem half solved.” - Charles F. Kettering
SCJP 6, OCPJWCD
Nidhi Sar wrote:Hold on a moment... why can't you update an object that you hold a lock to within synchronized method??
I hope that you know the difference between object and reference. Keeping that in mind, you can update an object to which you hold the lock. Example
The reason Joss' code didn't work is because we called the notify method on a different object and synchronized on a different object. The reference was the same, but the object was different. The original code does a work similar to the following code
Ankit Garg wrote:The reason Joss' code didn't work is because we called the notify method on a different object and synchronized on a different object. The reference was the same, but the object was different.
Thanks so much! That's great explanation. Somehow, I thought the following line was just changing the state of example1.total Integer object. But ofcourse, it creates a new object (unboxing, adding i, boxing) and gives it the same reference. My mistake
Abimaran Kugathasan wrote:If we don't synchronized both blocks(which have wait() and notify() methods within them), We don't get any Compilation error. But the 'communication' between them doesn't work. OK
If we don't call wait or notify method in synchronized context (synchronized on the object on which we are calling wait or notify), then we don't get any compilation error but an IllegalMonitorStateException at runtime...
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: IllegalMonitorStateException from notify()