• Post Reply Bookmark Topic Watch Topic
  • New Topic

Synchronization is not working as expected

 
rakesh kadulkar
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi this is my code


The problem is that.
I am not calling notify/notifyAll method in the synchronized method of calculator class then too my program is completing giving me the right output.

I think the program should not come out until and unless i call notify/all method from the synchronized block in the calculator class.


I am not able to find what is the problem with the code.

kindly try to find the solution together
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your problem is that you are extending Thread, then calling wait() on the Thread object. There is un-documented behavior regarding Thread and what happens when a Thread comes to an end. The part that is messing with your application is that when a Thread dies, it calls notifyAll() on the Thread object itself, so any wait()ers are woken up. This is not documented, so it can't be relied on - it is a side effect of some Thread implementation detail.

As a result, I use this as one of those reasons why it usually does NOT make sense to extend Thread. You should instead make both Reader1 and Calculator implement Runnable, not extend Thread. Then add start() methods which create new Threads and start them. Example:

 
Vijitha Kumara
Bartender
Posts: 3952
21
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Congrats Steve & Good luck on your Bartender role
 
rakesh kadulkar
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much as my problem is solved very nicely.

And sorry i forgot my java basics.

Well steve congrats for the new role as a "Bartender".

All the best.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys :-)

Glad its working for you now.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!