aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes thread 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 "thread" Watch "thread" New topic
Author

thread

sweety sinha
Ranch Hand

Joined: Jul 07, 2008
Posts: 76
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?
Rekha Srinath
Ranch Hand

Joined: Sep 13, 2008
Posts: 178


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.
M Srilatha
Ranch Hand

Joined: Aug 27, 2008
Posts: 137
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!


Thanks,<br />Srilatha M
sweety sinha
Ranch Hand

Joined: Jul 07, 2008
Posts: 76
thanks Rekha Srinath & M SRILATHA for your response
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: thread