简体   繁体   中英

Java Access singleton class instances from two Main class

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

  1. I run Main1 - So it will continue running and variable msg will be updated as "2" [ Here instance for SingletonObject class created ]

  2. 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?

You're running two completely separate programs, in two completely separate JVMs. A singleton is a singleton in its JVM.

JVMs don't have a shared memory. They're independent from each other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM