This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
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
Author

Synchronized methods Vs Synchronized blocks

bhadule bhadule
Greenhorn

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.....

Regards

Hrushi
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
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

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


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
 
subject: Synchronized methods Vs Synchronized blocks