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?
synchronized(AA.class)
, but no instances – Overflowobj
a syntax error? – Luge