what are read barriers and write barriers in synchronized block

前端 未结 4 1257
半阙折子戏
半阙折子戏 2021-01-12 04:44

I am looking into how a synchronized and volatile variable works in java and i came across a concept called read and write barrier . Can anyone help me to understand the mea

4条回答
  •  轮回少年
    2021-01-12 05:08

    Read and write barriers are used to implement the semantics of the Java Memory Model at the lowest level by JVMs.

    However that terminology is absent from the Java Language Specification, which only reasons in terms of happens-before relationships. In particular

    • a write to a volatile variable happens-before a subsequent read of that same variable
    • exiting a synchronized block happens-before a subsequent entry of that same syncchronized block

    When a happens-before relationship exists between two actions in your program, you have the guarantee that those two actions will be executed in a sequentially consistent order (i.e. as if there were only one thread and without unintuitive reorderings).

    Delving into the implementation details of the JVMs is unnecessary to write a correct multi-threaded program. However, if you want the gory details, the JSR-133 cookbook is an interesting read.

提交回复
热议问题