As long as you are right that this is caused by JIT, it has nothing to do with volatile.
Some JITs do internal optimizations on the fly and remove unnecessary code to speed things up, and this is exactly what happens here. JIT determines that comparing value != value always falsely and completely removes the entire block of code. In addition, it can determine that this for loop is now running empty and also removes the entire loop. As a result, this will be the final optimized verification class:
public void run() { System.out.println("nonEqualsCount = 0"); }
You can verify this by measuring the time it takes to complete this thread for each pass. On the first pass, it may take some time to finish, on the second it will be only a few nanoseconds for println.
Note. Typically, you cannot expect JIT to do anything. Based on actual implementation, hardware, and other factors, this may or may not optimize your code. And if it is optimized, the result is also impossible to determine, since, for example, the code can be optimized much earlier on slow equipment than on fast hardware.
Twothe
source share