Cardsox425
Cardsox425

Reputation: 11

Java while loop subtlety

I have the following code:

while(!loggedIn) {
    loggedIn = login.getDone();
}
System.out.println("madeIt");

The print line never executes, even though I know login.getDone() returns true at some point. If, however, I use the following code:

while(!loggedIn) {
    loggedIn = login.getDone();
    System.out.println(loggedIn);
}
System.out.println("madeIt");

Then the last print line executes. I have no idea why. Does anyone have any insight into why this happens?

For more code, see the entirety of my main class:

public class GameManager {
    public static void main (String args[]) {
        boolean loggedIn = false;
        String username;
        int playerNum;
        int i = 0;
        Login login = new Login();
        while (!loggedIn){
            loggedIn = login.getDone();
            //System.out.println(loggedIn);                                                                                                                                                                 
        }
        login.close();
    System.out.println("Logged in");
    }
}

and the entirety of the login class:

import squint.*;
import javax.swing.*;
import java.util.*;

public class Login extends GUIManager {
    private final int WINDOW_WIDTH = 200, WINDOW_HEIGHT = 150;

    private JButton login;

    String name;
    boolean done;
    int playerNumber;

    public Login() {
        done = false;
        this.createWindow( WINDOW_WIDTH, WINDOW_HEIGHT );
        this.setTitle("Hearts Login");
    login = new JButton("Click");

        contentPane.add(login);
    } 

    public void buttonClicked( ) {
        done = true;
        System.out.println(done);
    }

    public boolean getDone() {
        return done;
    }

}

And squint can be found at http://dept.cs.williams.edu/~cs134/squintV2.20.jar

Upvotes: 1

Views: 97

Answers (1)

OldCurmudgeon
OldCurmudgeon

Reputation: 65879

This could happen if loggeIn or the variable that getDone returns is set to true by another thread and it is not declared volatile.

It may be easier to determine your problem if you give a little more code.

Upvotes: 2

Related Questions