jQuery in Action, 3rd edition
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Synchronized methods Vs Synchronized blocks 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 "Synchronized methods Vs Synchronized blocks" Watch "Synchronized methods Vs Synchronized blocks" New topic

Synchronized methods Vs Synchronized blocks

bhadule bhadule

Joined: Sep 11, 2005
Posts: 10
Hello Ranchies,
can anybody plz explain me the difference between synchronized methods and synchronized blocks...i am reading the Khalid Mughal book, but it finds me difficult.....


Kevin Lam
Ranch Hand

Joined: Oct 27, 2005
Posts: 68
Hi there:

"When you synchronize a method, the object used to invoke the method is the object whose lock must be acquired. But when you synchronize a block of code, you specify which object´┐Żs lock you want to use as the lock, so you could, for example, use some third-party object as the lock for this piece of code. That gives you the ability to have more than one lock for code synchronization within a single object. " K&B

So I think syncrhonized block added the ability of specifying "a lock" rather than always using the current object's lock.

Hope this helps
Rob Spoor

Joined: Oct 27, 2005
Posts: 20269

Another difference is that with a synchronized method a lock is obtained for the duration of the entire method. With synchronized blocks you can specify exactly when the lock is needed.

Basically, synchronized blocks are more general, and synchronized methods can be rewritten to use synchronized blocks:

So synchronized methods are in fact only syntactical shortcuts

How To Ask Questions How To Answer Questions
I agree. Here's the link: http://aspose.com/file-tools
subject: Synchronized methods Vs Synchronized blocks
It's not a secret anymore!