• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Paragraph on threads (K&B)

 
Gian Franco
blacksmith
Ranch Hand
Posts: 979
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there,
I don't understand what is meant by the following
(bold) sentence on pg 523 of K&B:
When you synchronize a method, the object used to
invoke the method is the object whose lock must be
acquired. But when when you synchronize a block of
code, you specify which object's lock you want to
use as te lock, so you could, for example, use some
third-party object as the lock for this piece of code.



Can someone explain, thanks
Gian Franco
 
Phil Rhodes
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
it means that when you use the keyword synchronized inside a method to synchronize a portion of the method, you don't have to use "this" as the object to synchronize on. Every object in Java has a lock associated with it, and you can choose to use a different object other than your current class instance.
My own understanding of Java multi-threading is not great enough to explain all the details of WHY you'd want to do that... but IIRC, it's something like this. If you synchronize on "this", while you're in that block of code, you're blocking access to any other member functions of your class that are declared as synchronized (since you already have the one and only lock for "this" ). If whatever you're doing inside your function doesn't actually REQUIRE locking out all access to the entire instance, it's better to synchronize on something else, or you reduce the concurrency in your program, and hurt performance. I think maybe there's also some advantage in terms of avoiding deadlocks, but that's getting into area I'm not real stron g in , so I'll say no more.
Just to illustrate the point, here's some sample code (it doesn't actually DO anything mind you, but it demonstrates synchronizing on something other than "this" ).

[ February 01, 2004: Message edited by: Phil Rhodes ]
 
Gian Franco
blacksmith
Ranch Hand
Posts: 979
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Phil for the exhaustive answer
Greetings,
Gian Franco
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic