Does synchronized keyword prevent reordering in Java?

前端 未结 3 1604
长发绾君心
长发绾君心 2020-12-09 13:04

Suppose I have the following code in Java

a = 5;
synchronized(lock){
    b = 5;
}
c = 5;

Does synchronized prevent reordering? There is no

3条回答
  •  死守一世寂寞
    2020-12-09 13:32

    Does synchronized prevent reordering?

    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.

    There is no dependency between a, b and c.

    That makes no difference.

    Would assignment to a first happen then to b and then to c?

    Yes. But as has been noted, this is not guaranteed for all JVMs. (See below)

    If I did not have synchronized, the statements can be reordered in any way the JVM chooses right?

    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.

    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.

提交回复
热议问题