When InvalidMonitorStateException is thrown? why?


This exception is thrown when you try to call wait()/notify()/notifyAll() any of these methods for an Object from a point in your program where u are NOT having a lock on that object.(i.e. u r not executing any synchronized block/method of that object and still trying to call wait()/notify()/notifyAll())

wait(), notify() and notifyAll() all throw IllegalMonitorStateException. since This exception is a subclass of RuntimeException so we r not bound to catch it (although u may if u want to). and being a RuntimeException this exception is not mentioned in the signature of wait(), notify(), notifyAll() methods.
  1. class IllegalMonitorStateExample  
  2. {  
  3.   public static void main(String a[])  
  4.   {  
  5.     AnObject o = new AnObject();  
  6.     Thread inc = new Thread(new IncrUser(o));  
  7.     Thread dec = new Thread(new DecrUser(o));  
  8.     inc.start();  
  9.     dec.start();  
  10.   }  
  11. }  
  12.   
  13. class IncrUser implements Runnable  
  14. {  
  15.   AnObject a ;  
  16. IncrUser()  
  17. {  
  18. }  
  19.     IncrUser(AnObject a)  
  20. {  
  21. this.a = a;  
  22. }  
  23. public void run()  
  24. {  
  25. while(true)  
  26. {  
  27. try  
  28. {  
  29. [B]//   a.wait();[/B]  
  30.    a.incr();  
  31.    Thread.sleep(1000);  
  32. [B]  //   a.notify(); //[/B]  
  33. }  
  34. catch(InterruptedException ie)  
  35. {  
  36. ie.printStackTrace();  
  37. }  
  38.   
  39. }  
  40. }  
  41. }  
  42. class DecrUser implements Runnable  
  43. {  
  44.   AnObject a ;  
  45. DecrUser()  
  46. {  
  47. }  
  48.     DecrUser(AnObject a)  
  49. {  
  50. this.a = a;  
  51. }  
  52. public void run()  
  53. {  
  54. while(true)  
  55. {  
  56.             try  
  57. {  
  58.    a.decr();  
  59.    Thread.sleep(1000);  
  60. }  
  61. catch(InterruptedException ie)  
  62. {  
  63. ie.printStackTrace();  
  64. }  
  65.     }  
  66. }  
  67. }  
  68.   
  69. class AnObject{  
  70. int myNum = 0;  
  71. synchronized void incr() throws InterruptedException  
  72. {  
  73.   if(myNum!=0)  
  74.   {  
  75. System.out.println("ready to incr but muNum not zero +++++++++++++++");  
  76. wait();  
  77.   }  
  78.   myNum++;  
  79.   print("produced : ");  
  80.   notify();  
  81. }  
  82.  synchronized void decr() throws InterruptedException  
  83. {  
  84.   if(myNum==0)  
  85.   {  
  86.     System.out.println("ready to decr but myNum not 1 ----------");  
  87.     wait();  
  88.   }  
  89.   myNum--;  
  90.   print("consumed : ");  
  91.   notify();  
  92. }  
  93.   
  94. void print(String s)  
  95. {  
  96.     System.out.println(s + "  "+myNum);  
  97. }  
  98.   

1 comment: