What happens when a static synchronized method is called by two threads using different instances at the same time? Is it possible? The object lock is used for non static synchronized method but what type lock is used for static synchronized method?
-
1static methods ignore the instance variable if provided. It can even be `null` without error. For static methods the class object is used. – Peter Lawrey Sep 19 '12 at 10:08
-
1Discussed in http://stackoverflow.com/questions/437620/java-synchronized-methods-lock-on-object-or-class – yair Sep 19 '12 at 10:15
4 Answers
It is the same as synchronizing on the Class
object implementing the method, so yes, it is possible, and yes, the mechanism effectively ignores the instance fro which the method is called:
class Foo {
private static synchronized doSomething() {
// Synchronized code
}
}
is a shortcut for writing this:
class Foo {
private static doSomething() {
synchronized(Foo.class) {
// Synchronized code
}
}
}

- 714,442
- 84
- 1,110
- 1,523
It is possible.
The threads lock on the Class
object of the class, like on MyClass.class
.
See JLS, Section 8.4.3.6. synchronized Methods:
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.

- 8,945
- 4
- 31
- 50
static synchronized methods use locks on instance of type java.lang.Class. That is, each accessible class is represented by an object of type Class in runtime, and that object is used by static synchronized methods.

- 13,189
- 1
- 21
- 38
When using a static lock the objects are ignored. The lock is acquired on class rather than objects.

- 1
- 1