Does Java reordering affect System.currentTimeMillis()?

ぃ、小莉子 提交于 2019-12-06 17:04:22

问题


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?


回答1:


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.




回答2:


Due to being a user system call, compilers shouldn't reorder them in the same thread. If this was not true, we could even experience reordering effects in System.out.println(independent values); I guess that access to the System's/OS's clock creates a sort of relationship between these operations (always for the current thread), so theoretically there is some kind of dependency between them. Probably, JVM considers this issue and never reorders User System calls.



来源:https://stackoverflow.com/questions/27644045/does-java-reordering-affect-system-currenttimemillis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!