This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
Hi, I've stumble on a simple thread problem. I'd like to synchronized on the block of code instead of the whole method. However, my thread knowledge is weak and don't understand why I experience an IllegalMonitorStateException on the unlock method. (is my code an implementation of the condition to gain the ownership of a monitor specified in the Object's notify javadoc as "By executing the body of a synchronized statement that synchronizes on the object. ") I tried to trace into the method call. It seems that there is a exception in the lock, but it simply refuse to print the stack trace. I'd greatly apprecitate any explanation. Thanks so much.
Han Ming
Rob Ross
Bartender
Joined: Jan 07, 2002
Posts: 2205
posted
0
This one had me stumped for a bit until I realized your problem! Boolean types are immutable. You can't change their state. When you write isLocked = Boolean.FAlSE; or isLocked = Boolean.TRUE; you are not changing the state of the object, you are assigning a completely different object to the reference. This becomes an issue in your unlock() method:
You are synchronizing on one Boolean object, then the first thing you do is change the isLocked variable to contain a reference to a completely different Boolean object, which you do NOT have a lock on! That's why you get the IllegalMonitorState when you call notifyAll(). You're calling it on a different object than you synchronized on. Hope this helps! Rob
[ January 31, 2002: Message edited by: Shivaji Marathe ]
Rob Ross
Bartender
Joined: Jan 07, 2002
Posts: 2205
posted
0
Shivaji, you're doing the exact same thing that I said was the problem in the first place! You are calling wait() and notifyAll() for a different object than the one you synchronized on. You are synchronizing on isLocked, but you are calling wait() for the Lock object. You should be writing isLocked.wait() and isLocked.notifyAll();
Rob
Shivaji Marathe
Ranch Hand
Joined: Jan 11, 2002
Posts: 203
posted
0
Good catch.
HanMing Low
Ranch Hand
Joined: Oct 18, 2001
Posts: 196
posted
0
Hi Rob, Thanks for the explanation. It really didn't strike me that this was the reason. And it also helps in understanding other area in thread. Thanks so much.