In Java, what is the difference between synchronizing a block and synchronizing a static method?

Answered

In Java, what is the difference between synchronizing a block and synchronizing a static method?

Ninja Asked on 18th September 2018 in Java.
Add Comment
1 Answer(s)
Best answer

A synchronized method acquires a lock before it executes. For a static method, the lock associated with the Class object for the method’s class is used. For an instance method, the lock associated with this (the object for which the method was invoked) is used.

A synchronized block inside a method in Java is synchronized on the instance (object) owning the method. Thus, each instance has its synchronized methods synchronized on a different object: the owning instance. Only one thread can execute inside a Java code block synchronized on the same monitor object.

Synchronized static methods are synchronized on the class object of the class the synchronized static method belongs to. Since only one class object exists in the Java VM per class, only one thread can execute inside a static synchronized method in the same class.

Ninja Answered on 18th September 2018.
Add Comment