| 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: 19232
|
|
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
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: Synchronized methods Vs Synchronized blocks
|
|
|