This week's book giveaway is in the Agile forum.
We're giving away four copies of The Software Craftsman and have Sandro Mancuso on-line!
See this thread for details.
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

Win a copy of The Software Craftsman this week in the Agile forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "IllegalMonitorStateException" Watch "IllegalMonitorStateException" New topic


Asanka Vithanage
Ranch Hand

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

SCJP 1.5 (94%)
Ankit Garg

Joined: Aug 03, 2008
Posts: 9327

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.

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.

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:
subject: IllegalMonitorStateException