Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java synchronized static methods: lock on object or class

The Java documentation says:

It is not possible for two invocations of synchronized methods on the same object to interleave.

What does this mean for a static method? Since a static method has no associated object, will the synchronized keyword lock on the class, instead of the object?

like image 577
jbu Avatar asked Jan 13 '09 00:01

jbu


People also ask

Do synchronized methods synchronize on the object or the class?

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.

Is class level lock would be required for a synchronized static method?

Every class in Java has a unique lock which is nothing but class level lock. If a thread wants to execute a static synchronized method, then the thread requires a class level lock.

When a static method is synchronized what is locked?

In simple words a static synchronized method will lock the class instead of the object, and it will lock the class because the keyword static means: "class instead of instance". The keyword synchronized means that only one thread can access the method at a time.

What happens when I make a static method as synchronized?

Static Synchronized method is also a method of synchronizing a method in java such that no two threads can act simultaneously static upon the synchronized method. The only difference is by using Static Synchronized. We are attaining a class-level lock such that only one thread will operate on the method.


1 Answers

Just to add a little detail to Oscar's (pleasingly succinct!) answer, the relevant section on the Java Language Specification is 8.4.3.6, 'synchronized Methods':

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

like image 71
Cowan Avatar answered Oct 03 '22 03:10

Cowan