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.
The moose likes Java in General and the fly likes Thread causing Hang ?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Thread causing Hang ??" Watch "Thread causing Hang ??" New topic

Thread causing Hang ??

Sunny Jain
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

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..!!

Thanks and Regards,
SCJP 1.5 (90%), SCWCD 1.5 (85%), The Jovial Java, java.util.concurrent tutorial
Nitesh Kant

Joined: Feb 25, 2007
Posts: 1638

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.)

apigee, a better way to API!
Sunny Jain
Ranch Hand

Joined: Jul 23, 2007
Posts: 433

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..!!
I agree. Here's the link:
subject: Thread causing Hang ??
It's not a secret anymore!