4

I've noticed this bug (if it is a bug) and decided to make a test environment. Does anyone know if this is an actual problem or is it just me?

import java.util.Random;

public class Start {

    public static boolean value;

    public static void main(String[] args){
        Thread thread = new Thread(){
            @Override
            public void run(){
                random();
            }
        };
        thread.start();
        while(true){
            if(value) System.out.println("Done");
        }
    }

    public static void random(){
        while(true){
            value = new Random().nextInt(5) == 0;
        }
    }

}

I would expect this code to be spamming out "Done"s, but instead I get a bunch at the beginning and then no additions. When I modify the code as so:

while(true){
System.out.print(""); //Modification
    if(value) System.out.println("Done");
}

It starts spamming the "Done"s. Anyone know what's up? NOTE: I have tested this in an Eclipse environment and a compiled jar while using jdk 1.8.0 v.25 and jre 1.8.0 v.51.

Noah
  • 99
  • 1
  • 6

1 Answers1

3

I suspect that you hit a compiler optimization called hoisting - it recognizes that you overwrite value without having these changes "visible" to other threads and that's why it optimizes at some point and stops printing.

This behavior will change to what is likely the "wanted" behavior once you'll declare value as volatile - then updates to it become visible to other threads and then the printings will keep on forever.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129