What is the difference between synchronized
methods and synchronized
statements?
If possible, please use an example to make it more clear.
What is the difference between synchronized
methods and synchronized
statements?
If possible, please use an example to make it more clear.
synchronized
on method is locked on athis
object. It's equals tosynchronized (this) {}
Standard
synchronized
is locked on specified object/monitor. Withsynchronized (***) {}
you can choose an object to use for locking.A synchronized method locks the monitor associated with the instance of the class (ie 'this') or the class (if a static method) and prevents others from doing so until the return from the method. A synchronized block can lock any monitor (you tell it which) and can have a scope smaller than that of the encolsing method.
Synchronized blocks are prefered if they don't end up equivalent to the entire scope of the method and/or if they lock something less draconian than the instance (or class if static).
Quotes from the JLS (including example):
JLS 14.19 The
synchronized
StatementJLS 8.4.3.6
synchronized
MethodsSo how are they different?
A quotes from Effective Java 2nd Edition, Item 67: Avoid excessive synchronization:
The
synchronized
modifier for methods, being a syntactic sugar that it is, is applicable in many but not all scenarios. The book goes to discuss in much deeper detail why you should avoid excessive synchronization, but basically by usingsynchronized
statements, you have much greater control over the boundaries of yoursynchronized
regions (and if the scenario requires it, you can also choose your own locks).Unless your method is very simple and/or you need to acquire the
this
lock for the entire duration of the method (or theClass
object lock if the method isstatic
), you should usesynchronized
statements to limit the synchronization within the method to only to when you need it (i.e. when you're accessing shared mutable data).A
synchronized
method is a method whose body is encapsulated automatically in asynchronized
block.Thus, this is equal:
A synchronized method is one where you have, in effect, placed the entire body of the function in a synchronized block. A synchronized block has the advantage that you can apply the synchronized block to just a few select statements in the function, instead of to the function as a whole. In general, it is best to make synchronized blocks as short as possible, since time spent in synchronized blocks is time that some other thread might be prevented from doing meaningful work. Another distinction is that you can specify a particular object on which to apply the lock when using a synchronized block whereas with a synchronized method, the object, itself is automatically used as the lock on which synchronization is performed.