When a Java member needs to be thread-safe, we do like the following:
public synchronized void func() {
...
}
This syntax equivalent to:
public void func() {
synchronized(this) {
....
}
}
That is, it actually uses this
for a lock.
My question is, if I use synchronized
with a static
method, as follows:
class AA {
private AA() {}
public static synchronized AA getInstance() {
static AA obj = new AA();
return obj;
}
}
In this case, on what is the lock made for the synchronized
method?
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.
Indeed, it is not possible! Hence, multiple threads will not able to run any number of synchronized methods on the same object simultaneously.
Can two threads call two different synchronized instance methods of an Object? No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed.
First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
In case of static synchronized method, the class
object of your class AA
will be implicit lock
its equivalent to
class AA {
private AA() {}
public static AA getInstance() {
synchronized(AA.class) {
AA obj = new AA();
return obj;
}
}
}
From section 8.4.3.6 of the JLS:
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.
So your code acquires the monitor for AA.class
. As sanbhat says, it's like
synchronized(AA.class) {
...
}
... just as with an instance method it would be
synchronized(this) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With