I am referring to the solution for the Singleton Pattern by Bill Pugh on Wikipedia:
public class Singleton
{
// Private constructor prevents instantiation from other classes
private Singleton() {}
/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder
{
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance()
{
return SingletonHolder.INSTANCE;
}
}
Here they have mentioned:
The inner class is referenced no earlier (and therefore loaded no earlier by the class loader) than the moment that
getInstance()
is called. Thus, this solution is thread-safe without requiring special language constructs (i.e.volatile
orsynchronized
).
However, isn't there a possibility that 2 threads would call getInstance()
at the same time, which would lead to two instances of singleton being created? Isn't it safe to use synchronized
here? If yes, where should it be used in the code?