Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Lock Relinquishing......  RSS feed

 
Allen Bandela
Ranch Hand
Posts: 128
Eclipse IDE MS IE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Allen Bandela
Ranch Hand
Posts: 128
Eclipse IDE MS IE Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[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.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!