This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I have the following code, I am creating 5 thread here..all are executing till extinct..but one(sometimes 2 etc) thread is going for permanent wait..causing My system to hang..!! Can some one please help me to find out ..why this is happening and what is the solution to avoid this problem..!!
Hey Sunny, The problem is that you are incrementing the counter before getting into wait() (compounding the problem you do it before getting into synchronized block.) So, the counter does not really tell the number of threads waiting on the mutex. Thus, the notifyAll() in many cases will be called even before all the threads have gone into the waiting state and thus, the threads getting into wait() after notifyAll() will be stuck forever and never get a notify call. A simple soultion can be to keep on sending notification till all the threads have received it. This would mean that the counter will be incremented after return from wait and the notification thread keeps on notifying till the counter is 5 !!! (No points in telling that this is the most stupid way of handling wait-notify! But the logic you have is not something that a real system will have.)
Thanks a lot..!! I understand what you are trying to say..Actually I am practicing Threading so that I can apply them to real system..!! I do not feel very comfortable in Threading..!! I was even not aware of Atomization in Java..!! Well now i have gone through all..and feeling very comfortable now..!!