File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes Diff between Synchronized Block and Synchronized Method in Thread ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Diff between Synchronized Block and Synchronized Method in Thread ?" Watch "Diff between Synchronized Block and Synchronized Method in Thread ?" New topic
Author

Diff between Synchronized Block and Synchronized Method in Thread ?

Prabhat Ranjan
Ranch Hand

Joined: Oct 04, 2006
Posts: 391
Hi,

I gone through lot of discussion but it is not very much clear from there.
if some one can help me out on this.

What is understood:

1) Synchronized Block is used to lock the Any object while Synchronized method locks only this object.
2) In Synchronized block , first lock is acquired on object then method is called while in synchronized method first method is called then the lock is acquired.

is both is correct and any other differences are there , when to use which and why.

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38851
    
  23
Too difficult for "beginning". Moving thread.
Chris Hurst
Ranch Hand

Joined: Oct 26, 2003
Posts: 416
    
    2

1) Is correct (unless method is static)

2) In block you attempt to acquire the lock (whatever lock you've asked for) when you attempt to enter the actual block, in method you attempt to acquire the lock on 'this' pointer (or class object if static method) when you attempt to enter the method.

There are also subtle differences at a byte code level eg sync method is achieved with a flag on the method (ACC_SYNCHRONIZED).


"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Diff between Synchronized Block and Synchronized Method in Thread ?