Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java reordering affect System.currentTimeMillis()?

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?

like image 528
Kurtt.Lin Avatar asked Dec 25 '14 03:12

Kurtt.Lin


People also ask

How does system currentTimeMillis work in Java?

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.

What is reordering in Java?

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.


1 Answers

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.

like image 118
Joseph K. Strauss Avatar answered Oct 05 '22 22:10

Joseph K. Strauss