package Test
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = null;
public String msg = "1";
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
if(instance!=null){
}else{
instance = new SingleObject();
}
return instance;
}
package Test
public class Main1 {
public static void main(String[] args) {
SingleObject object = null;
while(true){
object = SingleObject.getInstance();
object.msg = "2";
System.out.println(object.msg); //Here output is 2
}
}
}
import SingleObject.*;
public class Main2{
public static void main(String[] args) {
//Here new instance being created
SingleObject object = SingleObject.getInstance();
//Here output is 1
System.out.println(object.msg);
}
}
After compiling both Main1 and Main2
I run Main1 - So it will continue running and variable msg will be updated as "2" [ Here instance for SingletonObject class created ]
Then I run the Main2 . But here new instance for SingleObject class created. So i am getting output as "1". As poer singleton desingn pattern. I should get instance created in Main1 when i run the Main2, why Main2 is creating new instance of SingletonObject?