I have gone through a singleton design pattern in Java which is below mentioned. I am having trouble to understand how does the Synchronized keyword in the public static getter or accessor method prevent more than one object creation ? If at all it is being called twice from two different classes Synchronized should make their calls Synchronized i.e. one after the other . How does it govern only one object creation? Please explain in details and also check the comments if my assumptions about the modifiers are correct or not
class MySingleton
{
private static MySingleton singletonObj; //as it is private it cannot be referenced outside of this class
//and as it is static all the instances of this class share the same copy of this refrence variable
private MySingleton()
{
System.out.println("Welcome to a singleton design pattern");
System.out.println("Objects cannot be instantiated outside of this class");
}
public static synchronized MySingleton getASingletonObject()
{
if(singletonObj==null)
{
singletonObj=new MySingleton();
}
return singletonObj;
}
}
Help is much appreciated :) Thanks