Java / Java Multithreading
Difference between synchronized method and synchronized block in Java.
A synchronized method uses the method receiver as a lock, 'this' for non static methods and the enclosing class for static methods. Synchronized blocks uses the expression as a lock.
A synchronized method locks on the object instance the method is contained in while a synchronized block can lock on ANY object.
For synchronized methods, the lock will be held throughout the method scope, while in the synchronized block, the lock is held only during that block scope also known as critical section.
Synchronized block can throw NullPointerException if the expression provided as parameter evaluates to null, which is not the case with synchronized methods.
Synchronized block provides granular control over lock, as you can use any lock to provide mutual exclusion to critical section code. Synchronized method always lock either on current object or class level lock, if its static synchronized method.
More Related questions...