I have a question about the synchronization on a singleton. Assume I have a singleton pattern like this:
public class Singleton {
private final Object obj;
private static Singleton instance;
private Singleton(Object obj) {
this.obj = obj;
}
public static synchronized Singleton getInstance(Object obj) {
if (instance == null) {
instance = new Singleton(obj);
}
return instance;
}
public synchronized void methodA() {
// ...
}
public synchronized void methodB() {
// ...
}
}
And I want to synchronize the access on it. I have two assumptions, that I need to verify.
Assumption: Every access on this Singleton is thread safe and synchronized, due to all methods being synchronized including the initializer.
Assumption: When I want to make sure that a thread that wants to call
methodA()
and then immediatelymethodB()
without another thread calling methods of the singleton, is it correct to synchronize on the instance like this?
Singleton singleton = Singleton.getInstance(obj);
synchronized (singleton) {
singleton.methodA();
singleton.methodB();
}
Explanation:
Is the 1. assumption correct because the synchronized on a not static method synchronizes on the object itself and since it is always the same object, the access is synchronized? And the call to getInstance(obj)
synchronizes on the class itself?
Is the 2. assumption correct because with the getInstance(obj)
every thread gets the same object and thus the synchronization is correct since another thread will wait till the synchronized block (...methodA(); methodB();
) is exited?