According to Java Memory Model, instructions can be reordered as long as the execution is well-formed.
So I wonder, is it possible that the following codes produces the following output?
[codes][in a same thread]
long a = System.currentTimeMillis();
long b = System.currentTimeMillis();
long c = System.currentTimeMillis();
[output]
a == 10, b == 20, c == 15
If not possible, then what does JVM / implementations do to prevent this from happening?
currentTimeMillis. Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
Instruction Reordering Increased parallelization means increased performance. Instruction reordering is allowed for the Java VM and the CPU as long as the semantics of the program do not change. The end result has to be the same as if the instructions were executed in the exact order they are listed in the source code.
Please see this question Instruction reordering & happens-before relationship in java.
I believe that unless you are in a different thread, the outcome of any execution will always be consistent with the order in your code. In this situation, since it is impossible to process it out of order, it should be good even if your fields are visible to another thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With