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?
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
}
}
}
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.
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.
When using a static lock the objects are ignored. The lock is acquired on class rather than objects.
© 2022 - 2024 — McMap. All rights reserved.
null
without error. For static methods the class object is used. – Lick