wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes IllegalMonitorStateException 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 "IllegalMonitorStateException" Watch "IllegalMonitorStateException" New topic
Author

IllegalMonitorStateException

Asanka Vithanage
Ranch Hand

Joined: Oct 24, 2008
Posts: 59
can any body explain the reason to genarate
IllegalMonitorStateException


SCJP 1.5 (94%)
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9304
    
  17

This exception occurs when you call wait or notify on an object whose lock is not held by the thread who is executing the code. Eg



To solve the problem, the code must be



SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
First Case:
If you wait or monitor on an object, without taking lock on that object means without synchronizing on that object, then IllegalMonitorStateException is thrown.




Second Case: If you take lock on an object, here synchronized(str),
but you change the object here str="String object changed here..";
and call wait() on that object here str.wait();
here str object has been changed. It is different Object than you have taken lock on. Now you donot have lock on new str object. so here if str.wait() called it will throw IllegalMonitorStateException, means your are monitoring on such an object that is not locked by you.



SCJP 6
Asanka Vithanage
Ranch Hand

Joined: Oct 24, 2008
Posts: 59
thnak you for you'r explanation...............

but i have problem.In the following code i used wait method without using synchronization .but it compiles and run fine
gives CDA as out put.but it not prints B in out put.
can You explain this

James Tharakan
Ranch Hand

Joined: Aug 29, 2008
Posts: 580

write a print statement in the catch block.


SCJP 6
Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
Asanka Vithanage
Ranch Hand

Joined: Oct 24, 2008
Posts: 59
:roll: :roll: :roll:
i got it
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: IllegalMonitorStateException