This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Hey there, I've been fighting with these for a couple of days and I hope one of ya'll can help me. I understand that the monitors wait and notifyAll have to be called from synchronized code and probably not the same piece of synchronized code either. But when I use 2 different methods and try to call notifyAll from the second synchronized method, I get illegalMonitorStateException error. Is this because the thread executing notifyAll doesn't have the lock on the waiting thread? I'm callling the start method so that the 2 threads will run concurrently but for the life of me I can't seem to be able to notify either one. They seem to hang on the wait() Can anyone help me? I'd introduce some code but it is really simple, try catch blocks with wait and notifyAll inside. Thx J
As far as I know, the only way you can get a IllegalMonitorStateException error is like you say, by calling one of the monitor related methods when the Thread is not synchronized on the object. As far as why your threads never get notified, I can't see where you expect that to happen. Bill ------------------ author of:
OK so where should I put the notifyAll() ? I tried it in the run method before the call to methodB and got IllegalMonitorStateException. I even created a new synchronized method called Notify and called notifyAll from there with yet a third thread. Same problem. My basic question is how to notify a waiting thread? Maybe I'm missing something but I just can't seem to get it to work at all. Any suggestions?? Thx J
Jay Brass, Hi there, Thing is that theres got to be a reason for synchronizing the two methods. Usually when two methods are dependent on each other. In your code both threads calls the mehtodA and are passed in to wait state. Try putting notifyAll() before the wait(), the code will work. I hope this helps. Regards. Jennifer.
Joined: Oct 24, 2000
Hey Jennifer, The only way I could get the results I wanted was to do this:
Which is little different than calling sleep(1000) except that sleep is static. I peppered the code with notifyAll()'s and still couldn't get it out of the wait state. I think because when notifyAll is called the notified thread can't aquire the lock because the other thread has it. So it is forced to wait again. Then the second thread waits and no one ever notifies it. Can someone verify this? And can someone tell me where I can apply a notifyAll command to give me the same results as above? Thx J
Joined: Oct 24, 2000
sorry there should be a new SimpleThreads("Thread 2").start(); included in the above code. Darn that cut and paste! J