I have a multithreaded application and a singleton class:
public final class Singleton {
private static MyClass mc;
public static final Object getInstance() {
if(mc == null) {
mc = new MyClass();
}
return mc;
}
}
Of course, this will not work in a general multithreaded scenario. But consider the following scenario:
- In the beginning there is only one thread
- This one thread calls
getInstance()
for the first time so that mc is initialized. - After that all other threads are started by the first thread.
My assumption:
This should work because the initialization of the mc
field and the object's construction happen-before all subsequent Thread.start()
calls that start the other threads. And the Thread.start()
for a thread happens-before all other actions of that thread. It follows that the initialization of mc
happens-before all actions in all other threads so that getInstance()
will return the right value for all threads.
Is this assumption right? Why / Why not?
final MyClass singleton = new MyClass();
it's eager and perfectly threadsafe - en.wikipedia.org/wiki/Singleton_pattern#Eager_initialization - lazy initialization has only benefits if there are chances that this class is just partially required long before you'll need the instance. In most cases, class loading (=static initialization) is the exact same time you need the singleton. – King