[FIXED] Java – while(true) loop not checking, if condition is true, if the else statement is missing

Issue

public class Main {

    public static boolean isToggled = false;
    public static boolean isClicking = false;

    public static void main(String[] args){
        while(true){
            if(Main.isToggled && Main.isClicking){
                System.out.println("Running");
            }            
        }
    }

I have two public static booleans with the value of false in my Main class.

A while(true) loop will constantly check, if both booleans are set to true, by another class.

However, if both conditions are being set to true, nothing happens.

The while loop only works, if an else statement is added to it like this:

public class Main {

    public static boolean isToggled = false;
    public static boolean isClicking = false;

    public static void main(String[] args){
        while(true){
            if(Main.isToggled && Main.isClicking){
                System.out.println("Running");
            }
            else{
                System.out.println("Idle");
            }            
        }
    }

So it is definitely the while loop that is the problem.

The class which sets the conditions to true works perfectly fine. I’ve tested that by removing the while loop, and just printing the value of the booleans after their value has changed.

I don’t understand, why the first code isn’t doing what its supposed to, when the other one with the else statement added to it does.

Copy code to test:

public class Main {

    public static boolean isToggled = false;
    public static boolean isClicking = false;

    public static void main(String[] args) {

        Thread changeBoolsT = new Thread(new Runnable() {
            @Override
            public void run() {
                changeBools();
            }
        });
        changeBoolsT.start();


        while(true){
            if(isToggled && isClicking){
                System.out.println("OK");
                break;
            }
            else{ // Remove this else statement
                System.out.println("Waiting");
            }
        }
    }

    public static void changeBools(){
        try{
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        isToggled = true;
        isClicking = true;
    }
}

Solution

The JVM will optimize your code, because the value is never changed in your main thread. There is no synchronization happening between threads. You need to use synchronized blocks when reading and writing the variables or mark them as volatile. volatile will force them to be read anew from memory every time they are accessed.

Answered By – knittl

Answer Checked By – Marie Seifert (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published