简体   繁体   English

Java重新排序会影响System.currentTimeMillis()吗?

[英]Does Java reordering affect System.currentTimeMillis()?

According to Java Memory Model, instructions can be reordered as long as the execution is well-formed . 根据Java Memory Model,只要执行结构良好 ,指令就可以重新排序。

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? 如果不可能,那么JVM /实现会做些什么来防止这种情况发生?

Please see this question Instruction reordering & happens-before relationship in java . 请参阅此问题指令重新排序和发生在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. 在这种情况下,由于无法按顺序处理它,即使您的字段对另一个线程可见,它也应该是好的。

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); 如果不是这样,我们甚至可以在System.out.println(独立值)中体验重新排序效果; 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. 我想对System / OS的时钟的访问在这些操作之间创建了一种关系(总是针对当前线程),所以理论上它们之间存在某种依赖关系。 Probably, JVM considers this issue and never reorders User System calls. 可能JVM会考虑此问题,并且永远不会重新排序用户系统调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM