Java synchronized static methods: lock on object or class Java synchronized static methods: lock on object or class java java

Java synchronized static methods: lock on object or class


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.


Since a static method has no associated object, will the synchronized keyword lock on the class, instead of the object?

Yes. :)


One point you have to be careful about (several programmers generally fall in that trap) is that there is no link between synchronized static methods and sync'ed non static methods, ie:

class A {    static synchronized f() {...}    synchronized g() {...}}

Main:

A a = new A();

Thread 1:

A.f();

Thread 2:

a.g();

f() and g() are not synchronized with each other and thus can execute totally concurrently.