问题描述
假设我在Java中有以下代码
Suppose I have the following code in Java
a = 5;
synchronized(lock){
b = 5;
}
c = 5;
同步会阻止重新排序吗? a,b和c之间没有依赖关系。分配给第一个然后发生到b然后发生到c?如果我没有同步,那么语句可以以JVM选择的任何方式重新排序吗?
Does synchronized prevent reordering? There is no dependency between a, b and c. Would assignment to a first happen then to b and then to c? If I did not have synchronized, the statements can be reordered in any way the JVM chooses right?
推荐答案
它会阻止一些重新排序。您仍然可以在synchronized块之外和synchronized块内重新排序,但不能从synchronized块内部重新排序到它之外。
It prevents some re-ordering. You can still have re-ordering outside the synchronized block and inside the synchronized block, but not from inside a synchronized block, to outside it.
这没什么区别。
是的。但正如已经指出的那样,并不是所有JVM都能保证这一点。 (见下文)
Yes. But as has been noted, this is not guaranteed for all JVMs. (See below)
是的,是由JVM和/或CPU指令优化器和/或CPU缓存,但不可能没有明显的理由怀疑改变a = 5的顺序;和b = 5;将提高性能。
Yes, by the JVM and/or the CPU instruction optimiser and/or CPU cache, but it is unlikely given there is no obvious reason to suspect that changing the order of a = 5; and b = 5; will improve performance.
您可以看到更改缓存的可见性。即读取这些值的另一个线程可以看到b = 5;在a = 5之前;例如它们位于不同的缓存行中,如果它还没有同步。
What you could see is a change of visibility for the cache. i.e. another thread reading these values could see the b = 5; before a = 5; e.g. they are on different cache lines, if it is not also synchronized.
这篇关于synchronized关键字是否会阻止Java中的重新排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!