In Java, what is the difference between synchronizing a block and synchronizing a static method?
In Java, what is the difference between synchronizing a block and synchronizing a static method?
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.