-2

Can someone please tell me whether its more efficient to synchronize on a method or a block in Java?

Just thinking about this, when you synchronize on something it affects the performance so I would assume that synchronizing on a block is preferential to synchronizing on a method as it takes up less code - is this always the case?

maloney
  • 1,633
  • 3
  • 26
  • 49
  • Why all the downvotes? Seriously, i just wanted to know the answer to a question - in future i wont bother – maloney Apr 04 '13 at 10:27
  • @maloney I assume the downvotes are for not doing any research for existing questions/answers on this site. – A.H. Apr 04 '13 at 10:31
  • @A.H. all the answers i could find were to do with when you would use synchronized on a method or a block - not which one was more efficient... – maloney Apr 04 '13 at 10:33

1 Answers1

4

If you synchronize the method, then the whole method is synchronized so only one thread can execute that method at a time. If you synchronize a code block within that method then more than one thread can execute the method simultaneously, but only one thread can enter the synchronized block at a time.

From this we can conclude that synchronizing on the smallest possible code block required is the most efficient way to do it. However the practical difference between synchronizing a method vs. a code block really depends on the method and what code is being left out of the synchronized block.

Thorn
  • 4,015
  • 4
  • 23
  • 42