The conditional statement at the beginning of the while loop is not checked

I noticed this error (if it is an error) and decided to create a test environment. Does anyone know if this is really a real 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 expect this code to be "Done", but instead I get a bunch at the beginning, and then no extras. When I change the code like this:

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

He starts the Done mailing list. Does anyone know what? NOTE. I tested this in an Eclipse environment and a compiled jar using jdk 1.8.0 v.25 and jre 1.8.0 v.51.

+4
source share
1 answer

I suspect that you have chosen to optimize the hoisting compiler - it recognizes that you are overwriting value without changing these changes to other threads, and therefore it optimizes at some point and stops printing.

This behavior will change to what is likely to be "desirable" as soon as you declare value as volatile - then the updates will become visible to other threads, and then printing will continue forever.

+3
source

All Articles