| Author |
Diff between Synchronized Block and Synchronized Method in Thread ?
|
Prabhat Ranjan
Ranch Hand
Joined: Oct 04, 2006
Posts: 361
|
|
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: 32830
|
|
|
Too difficult for "beginning". Moving thread.
|
 |
Chris Hurst
Ranch Hand
Joined: Oct 26, 2003
Posts: 376
|
|
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
|
 |
 |
|
|
subject: Diff between Synchronized Block and Synchronized Method in Thread ?
|
|
|