The javac
compiler does not perform any optimizations.
The native JIT compiler can reorder instructions where there is a problem with memory ordering. However, the CPU can also reorder instructions and memory updates that have the same effect.
What is achieved by allowing this freedm compiler?
The main benefit is code portability. The more guarantees you provide, the more difficult it is to provide each platform in reality.
There is also a significant performance improvement, allowing the processor to execute instructions as and when possible, rather than in strict order.
Is it possible for the compiler to be able to create code that is more efficient at reordering the code?
Yes. but the reordering performed by the processor is more significant.
I have yet to see a practical matter. Sometimes I feel that the benefits, if any, are far outweighed by the concurrency risks that may arise.
Is there a way that a programmer can tell the compiler not to rearrange lines like this?
This is why you use memory barriers such as volatile
, synchronized
and Lock
blocks. When you use them, you get thread safety guarantees.
I know that using synchronization primitives effectively handles the side effects of permutation, but I ask, is there any direct way (compiler option) to disable this?
You can disable JIT, but most reordering is done by the processor, so it will not achieve significant results.
Avoiding reordering updates is such a small part of the thread's security problem (the biggest problem is that it is unclear and rarely occurs, making it difficult to test). And as soon as you write safe thread code, this makes it easier.