File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Diff between Synchronized Block and Synchronized Method in Thread ?

 
Prabhat Ranjan
Ranch Hand
Posts: 397
  • 0
  • 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
Pie
Posts: 47293
52
  • 0
  • 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
  • 0
  • 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).
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic