Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

K&B book example

 
Sahil Kapoor
Ranch Hand
Posts: 316
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code is given in K&B book in chapter Threads.
When i tried Running it....It is giving Exception, i am not understanding why it is giving ???



Runtime error :-

java ThreadTesting
Exception in thread "Thread-3" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at ThreadB.run(ThreadTesting.java:23)
4950



Moreover i am also not understanding why it is being assumed that after b.start() main thread continues and synchronized(b) would be executed.
It may also happen that threadB executes first, gets the lock and calculates total and then synchronized(b) would get executed. If it may happen then what is the use of b.wait() ....infact threadB is already done and now no notification would also come from it. A full chaos....

Please anyone explain this wait() notify() confusion.

All hell broke Lose !!!
 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sahil Kapoor wrote:The following code is given in K&B book in chapter Threads.
When i tried Running it....It is giving Exception, i am not understanding why it is giving ???

a call to notify is outside a synchronized block.
Look here: http://java.sun.com/javase/6/docs/api/java/lang/Object.html#notify%28%29
Throws:
IllegalMonitorStateException - if the current thread is not the owner of this object's monitor.


Sahil Kapoor wrote:It may also happen that threadB executes first, gets the lock and calculates total and then synchronized(b) would get executed. If it may happen then what is the use of b.wait() ....infact threadB is already done and now no notification would also come from it. A full chaos....

Yes, you are right - it may happen. In this case wait() will hang and will wait forever.
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What would happen?
 
Lalit Mehra
Ranch Hand
Posts: 384
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it won't notify any other threads waiting to hold lock on that objects monitor then
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic