Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

IllegalMonitorStateException

 
Asanka Vithanage
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can any body explain the reason to genarate
IllegalMonitorStateException
 
Ankit Garg
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 580
Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
write a print statement in the catch block.
 
Asanka Vithanage
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
:roll: :roll: :roll:
i got it
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic