This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Diff between Synchronized Block and Synchronized Method in Thread ?

 
Prabhat Ranjan
Ranch Hand
Posts: 397
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48415
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Too difficult for "beginning". Moving thread.
 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic