• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Practice question on synchronized

 
Vad Fogel
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, here's a question on using sync-ed blocks and calling wait(). Check the three correct options.
 
Pradeep bhatt
Ranch Hand
Posts: 8927
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
B,E,G
 
Lakshmi Saradha
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is this producing an IllegalMonitorStateException? (in the line where the wait method is called).
 
Vad Fogel
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Y this is producing Exception can any one explain
regs
Vivek Nidhi
 
Vad Fogel
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instead of locking 'sb' object, if 'synchronized (this )' is used
then the run time exception would vanish .
 
Vivek Nidhi
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks every one
Vivek nidhi
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic