Home > front end >  Why accessing Java static fields from another class gives wrong values?
Why accessing Java static fields from another class gives wrong values?

Time:09-07

public class Server {

    private static boolean msgForAlice=false;
    private static boolean msgForBob=false;

    public static void shouldAliceWait() {
        System.out.println(msgForAlice);
        System.out.println(msgForBob);
    }

    public static void main(String[] args) {
        System.out.println("Before:");
        System.out.println(msgForAlice);
        System.out.println(msgForBob);
        
        try {
            Thread.sleep(2000);
        }catch(Exception e) {
            e.printStackTrace();
        }
        
        msgForBob=true;
        System.out.println("After:");
        System.out.println(msgForAlice);
        System.out.println(msgForBob);
        
        try {
            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
            console.readLine();
        }catch(Exception e) {
            e.printStackTrace()
}}

public class Test {

    public static void main(String[] args) {
        Server.shouldAliceWait();
    }
    
}

When main method of class Test is called while Server's main method is beeing blocked by readLine() call, I get unusual values from Server's static fields:

Server:
Before:
false
false
After:
false
true

Test:
false
false

Can someone explain me?

CodePudding user response:

It's quite simple: in Java you can only ever run a single starting point (main method). If you have 2 main methods and you are running each one, it means you are running 2 instances of your program. If you're running 2 instances of your program, they don't share each other's information or variables.

When main method of class Test is called while Server's main method is beeing blocked by readLine() call, I get unusual values from Server's static fields:

So if you are doing this, it means you must have instantiated Java twice - once for the first main method in its own space and a second time for the second main method also in its own space. If that's the case, they're not sharing information.

  •  Tags:  
  • java
  • Related