• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

thread

 
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
this code is from: SCJP 6 Mock exam for Threads � Niko�s java blog.mht



it print A and gives runtime exception

but if modified like this it compiles and run fine


so why first code is getting exception and second code runs fine?
 
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


In Line 1, you are synchronizing on a newly created object but on Line 2, you are calling notifyall () on an entirely-different object that is newly created again.
 
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
wait(), notify(), and notifyAll() must be called from within a synchronized
context! A thread can't invoke a wait or notify method on an object unless it owns that object's lock.


In the first code sample, main thread has acquired lock on the object which is created in 2 line and its invoking the notifyAll() method on a new objet which is created inside the synchorized block. As the main thread doesnt own the lock on the object on which notifyAll() is invoked, it will throw runtime exception "IllegalMonitorStateException".

In the second example, the thread is trying to invoke the notifyAll() method on object r and it owns the lock on r. Thats the reason code compiles and runs properly!
 
sweety sinha
Ranch Hand
Posts: 76
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks Rekha Srinath & M SRILATHA for your response
 
It's hard to fight evil. The little things, like a nice sandwich, really helps. Right tiny ad?
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic