aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Practice question on synchronized Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Practice question on synchronized" Watch "Practice question on synchronized" New topic
Author

Practice question on synchronized

Vad Fogel
Ranch Hand

Joined: Aug 25, 2003
Posts: 504
Hi, here's a question on using sync-ed blocks and calling wait(). Check the three correct options.
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8919

B,E,G


Groovy
Lakshmi Saradha
Ranch Hand

Joined: Oct 21, 2003
Posts: 170
Why is this producing an IllegalMonitorStateException? (in the line where the wait method is called).


Thanks,<br />Lakshmi.
Vad Fogel
Ranch Hand

Joined: Aug 25, 2003
Posts: 504
It feels like almost nobody wants to dig this question. Well, B, G, and E should be an incorrect option altogether.
Vivek Nidhi
Ranch Hand

Joined: Aug 10, 2003
Posts: 133
Y this is producing Exception can any one explain
regs
Vivek Nidhi
Vad Fogel
Ranch Hand

Joined: Aug 25, 2003
Posts: 504
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.
Sunder Ganapathy
Ranch Hand

Joined: Apr 01, 2003
Posts: 120
Instead of locking 'sb' object, if 'synchronized (this )' is used
then the run time exception would vanish .
Vivek Nidhi
Ranch Hand

Joined: Aug 10, 2003
Posts: 133
Thanks every one
Vivek nidhi
 
 
subject: Practice question on synchronized