Question

I have a really strange problem with java under Debian. On windows this works:

boolean X=true;
while(X);

This code performs a loop while X is true, when i set X to false the while loop ends. The problem is that on Debian the SAME code, when i set X to false, the while loop does not stop.

If I modify the the code:

boolean X=true;
while(X) {
    System.out.println("hello");
}

This code works fine on Debian but only if I add the print statement. If I try i++ for example it doesn't work correctly, only with the print statement it works.

Why is my code handled differently on a different OS?

Was it helpful?

Solution

If non-volatile variable is accessed from other thread, the behavior may be unpredictable: it may be cached on the current thread. Try to define X as volatile:

volatile boolean X = true;

Take a look at: Do you ever use the volatile keyword in Java?

OTHER TIPS

I found this to give interesting results depending on the processor's architecure x86 vs 64bits.

public class WhileTrueTest
{
    boolean keepGoing = true;
    volatile boolean volatileKeepGoing = true;

    public static void main( String[] args ) throws InterruptedException
    {
        new WhileTrueTest().go();
    }

    private void go() throws InterruptedException
    {
        final Thread tNormal = new InnerNormal();
        final Thread tVolatile = new InnerVolatile();
        tNormal.start();
        tVolatile.start();
        Thread.sleep( 1000 );
        keepGoing = false;
        volatileKeepGoing = false;
        Thread.sleep( 1000 );
        System.out.printf("Threads shouldn't be alive. Are they? Normal:%s Volatile:%s", 
           tNormal.isAlive(), 
           tVolatile.isAlive());
        System.out.println();
        System.exit(1);

    }

    class InnerNormal extends Thread
    {
        @Override
        public void run()
        {
            while(keepGoing) {}
        }

    }

    class InnerVolatile extends Thread
    {
        @Override
        public void run()
        {
            while(volatileKeepGoing) {}
        }
    }        
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top