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.
Y this is producing Exception can any one explain regs Vivek Nidhi
Joined: Aug 25, 2003
Originally posted by Vivek Nidhi: Y this is producing Exception can any one explain regs Vivek Nidhi
The sync-ed block of code in MyRunnable allows one thread at a time to execute the code inside the run() method. Any thread that has acquired a lock on sb object can do it. The call to wait() looks like a perfectly legal request to put the currently executing thread to wait while making it release the lock on sb. However, it's not what's happening in the code! This call to wait() would be good if the current thread had a lock on MyRunnable thread target object! You can think of wait(); as this.wait(); The thread entering the sync-ed block doesn't hold the lock on the currently executing instance of MyRunnable. Therefore, an IllegalMonitorStateException gets thrown. To avoid it, one should call wait on sb like that: sb.wait(); or make the whole run() sync-ed. Figuring out the rest of correct answers follows the glitch above. Please let me know if anything was worded ambiguously. Otherwise, I hope this small gotcha helps learn the concept.