First of all, javac almost never optimizes the code, you’re compiling. Only when the values are compile-time constants, javac is required to evaluate expressions at compile-time, which itself form compile-time constants, see JLS §15.28. Constant Expressions.

However, operations get optimized at runtime and it is even the absence of thread synchronization measures that allows the optimizer to use optimistic assumptions, like that a variable won’t change between two reads. So the n!=n expression starts with a low likelihood of ever evaluate to true due to the short time between the reads¹ and will almost never be true after the optimizer kicked in. So while the expression n!=n is not guaranteed to be always false, it’s unlikely to ever encounter it to be true in practice.

Of course, according to Murphy’s Law, it will never happen when you try to provoke that error anyway, but once in a while at the customer, but never reproducible…

¹ Note that even if the second thread reads the initial 0 value due to the race condition, n!=n will only fail, if does not read the initial 0 again in the subsequent read.

Email codedump link for How to understand an example of book java concurrency in practice?