Hi ,
I was refering to a solution from wikipedia for Singleton Pattern:
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;
}
}
This can be found at http://en.wikipedia.org/wiki/Singleton_pattern under The solution of Bill Pugh
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 or synchronized).
However, isnt there a possibility that 2 threads would call getInstance() method at the same time which would lead to two instaces of singleton being created . Isnt it safe to use synchronized here. If Yes, where should it be used in the code.
Thanks