Does synchronized keyword prevent reordering in Java?

前端 未结 3 1599
长发绾君心
长发绾君心 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:40

    Locking the assignment to b will, at the very least, introduce an acquire-fence before the assignment, and a release-fence after the assignment.

    This prevents instructions after the acquire-fence to be moved above the fence, and instructions before the release-fence to be moved below the fence.

    Using the ↓↑ notation:

    a = 5;
    ↓ 
    b = 5;
    ↑
    c = 5;
    

    The ↓ prevents instructions from being moved above it. The ↑ prevents instructions from being moved below it.

提交回复
热议问题