| Author |
Lock Relinquishing......
|
Allen Bandela
Ranch Hand
Joined: Feb 16, 2006
Posts: 127
|
|
Hi! Q 1. I enter a synchronized block, throw an Exception and enter a catch block. At what point did I release the lock ? When I threw an Exception, or when I finished the catch block or did I never? Q 2. Does making the lock object static, have any influence on any threads ability to execute? thanks [ July 19, 2006: Message edited by: Allen Sylvester ]
|
Life is like a day. If the day is of no use, neither a month or a year.
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24061
|
|
1) When you exit the synchronized block. If the synchronized block is inside the "try", then yes, it effectively happens when the exception is thrown. If on the other hand the try/catch is entirely inside the synchronized block, then you don't let go of the monitor at any time inside the catch block. 2) Remember that objects aren't static; only fields can be static. We lock objects, not fields, so the fact that an object is held in a static field has no effect at all on synchronization.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Allen Bandela
Ranch Hand
Joined: Feb 16, 2006
Posts: 127
|
|
|
Thanks Ernest for clearing the doubt about static fields and not objects. Now, it makes sense . I was getting into a tangle imagining otherwise.
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
|
|
[Allen]: Q 2. Does making the lock object static, have any influence on any threads ability to execute? [EFH]: 2) Remember that objects aren't static; only fields can be static. We lock objects, not fields, so the fact that an object is held in a static field has no effect at all on synchronization. I would note that if you're synchronizing using a static reference, then in general you are probably more likely to run into thread contention than if you synchronize using a nonstatic reference. That is, it's more likely that two differerent threads will synchronize using the same instance (since the static reference is shared by everyone), which would cause the second thread to block until the first one exits the sync block. That's not an absolute rule; I can imagine counterexamples. But I think it's true as a general rule. Of course sometimes it's very much necessary to synchronize using a static reference. Just be aware that it could well be slower than sync on a nonstatic reference. Analyze the situation and do it if it's necessary; avoid it if it's not.
|
"I'm not back." - Bill Harding, Twister
|
 |
 |
|
|
subject: Lock Relinquishing......
|
|
|