by BehindJava

What is the difference between a synchronized method and synchronized block in Java

Home » java » What is the difference between a synchronized method and synchronized block in Java

This is a quick tutorial on the differences between synchronized method and synchronized block in Java.

The key difference is this:

If you declare a method to be synchronized, then the entire body of the method becomes synchronized; if you use the synchronized block, however, then you can surround just the “critical section” of the method in the synchronized block, while leaving the rest of the method out of the block.

If the entire method is part of the critical section, then there effectively is no difference. If that is not the case, then you should use a synchronized block around just the critical section. The more statements you have in a synchronized block, the less overall parallelism you get, so you want to keep those to the minimum.

A synchronized method uses the method receiver as a lock (i.e. this for non static methods, and the enclosing class for static methods). Synchronized blocks uses the expression as a lock.

So the following two methods are equivalent from locking prospective:

synchronized void mymethod() { ... }

void mymethod() {
  synchronized (this) { ... }

For static methods, the class will be locked:

class MyClass {
  synchronized static mystatic() { ... }

  static mystaticeq() {
    syncrhonized (MyClass.class) { ... }

For synchronized blocks, you can use any non-null object as a lock:

synchronized (mymap) {
  mymap.put(..., ...);

Lock scope

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 (otherwise known as critical section). In practice, the JVM is permitted to optimize by removing some operations out of the synchronized block execution if it can prove that it can be done safely.