aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Paragraph on threads (K&B) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Paragraph on threads (K&B)" Watch "Paragraph on threads (K&B)" New topic
Author

Paragraph on threads (K&B)

Gian Franco
blacksmith
Ranch Hand

Joined: Dec 16, 2003
Posts: 977
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


"Eppur si muove!"
Phil Rhodes
Ranch Hand

Joined: Dec 27, 2003
Posts: 65
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 ]

A+, Network+, SCJP, SCWCD<br />preparing for SCBCD, SCEA, CompTIA I-Net+
Gian Franco
blacksmith
Ranch Hand

Joined: Dec 16, 2003
Posts: 977
Thanks Phil for the exhaustive answer
Greetings,
Gian Franco
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Paragraph on threads (K&B)