The volatile modifier can be used to inform the compiler that it should not attempt to perform optimizations on the field, which could cause unpredictable results when the field is accessed by multiple threads.
What does optimizations mean here? Please explain.
The volatile keyword is not used very much in Java, it is much more common in C. The optimizations are something like this: What if we have a field x that can be changed from within some other process and we write the code
An optimizing compiler could say "well, in the line above the if, x is assigned the value 5, so of course it is greater than 3. We don't need the if because it will always evaluate to true" and promptly changes your code to
By declaring x as volatile, however, you tell the compiler that x can be changed between the line "x = 5;" and the if construct, so it will not assume that the value will still be 5.
I'm saying that some optimizing compilers are definitely smart enough to notice when for instance an if construct will always be evaluated as true (or false) and therefore remove the test (or, in the case of always false, it could discard the entire block), after all, why test for a condition that will always be true?
Notice, this is not restricted to if constructs, any type of control structure can be optimized if the compiler sees that it can evaluate it at compile time.