File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronized methods Vs Synchronized blocks

 
bhadule bhadule
Greenhorn
Posts: 10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 68
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20398
47
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic