Search code examples
javavariablesscopepass-by-value

Affecting variables in different classes in Java


I have two classes that I'm trying to manipulate one variable with, as an example

public class A {

    public static void main(String[] args) {

        while(game_over[0] == false) {
            System.out.println("in the while-loop");
        }
        System.out.println("out of the while-loop");
    }

    static boolean[] game_over = {false};
}

and

public class B {

    public boolean[] game_over;

    public printBoard(boolean[] game_over) {

        this.game_over = game_over;
    }

    public void run() {

        for (int i = 0; i < 10; i++) {
            // do something
        }
        game_over[0] = true;
        System.out.println("GAME OVER");
    }
}

The code snippets provided are not meant to be actual workable code, I'm more concerned with the concept. In my program, class A creates a thread that utilizes class B, and I want class B to affect the variable 'game_over' such that the while-loop in class A will be affected by the change... any idea how I can successfully update the variable? Thanks.


Solution

  • Don't use an array for this, that makes it harder to ensure a data-race free application.

    Since you want to be able to pass around the game_over flag as an independent object, the easiest way to achieve a correct multi-threaded application is to use the AtomicBoolean class.

    import java.util.concurrent.atomic.AtomicBoolean;
    
    class B {
        private AtomicBoolean game_over;
    
        public B(AtomicBoolean game_over) {
            this.game_over = game_over;
        }
    
        public void run() {
            // do stuff
            game_over.set(true);
        }
    }
    

    and in your class A:

    public class A {
        static AtomicBoolean game_over = new AtomicBoolean();
    
        public static void main(String[] args) {
            B b = new B();
            Thread t = new Thread(b);
            t.start();
    
            while (!game_over.get()) {
                System.out.println("in the while-loop");
            }
            System.out.println("out of the while-loop");
        }
    }