Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

synchronized block vs. synchronized method  RSS feed

 
rama murthy
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why would you use a synchronized block vs. synchronized method?
 
Jan Groth
Ranch Hand
Posts: 456
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a synchronized block can be smaller and perform some additional logic embracing the synchronization. that's one issue.

the second issue in my eyes is the fact that with a synchronized block you can synchronize on whatever (object) you want, while a method synchronizes on its class object, which is beyond your control.

hope it helps,
jan
 
rama murthy
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply.

Regarding your first point even synchronizeds methods can be smaller right?

I agree with your second point.
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jan Groth:

with a synchronized block you can synchronize on whatever (object) you want, while a method synchronizes on its class object, which is beyond your control.


I think you mean:
1. static synchronized methods synchronize on the class object
2. non-static synchronized methods synchronize on "this"
 
Jan Groth
Ranch Hand
Posts: 456
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@jeff

... obviously you are right :-)

@rama

a synchronized method can get as small as this example:

... but not smaller.

cheers,
jan
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My conclusions on synch block -vs- synch method have always been:

1. The synch method is syntactic sugar, since these two are equivalent:

and similarly for static methods.

2. Sometime a little sugar is OK. For methods where I would put the whole body in the synchronized(this) block, I see nothing wrong with using the synchronized method syntax. But it's easy to get lazy: sometimes the synchronized code doesn't have to be the whole method body -- and it's a good idea to make it as small as possible. I think about this issue more when using the synchronized block that when using the synchronized method syntax. But maybe it's just me...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!