当前位置:网站首页>jvm-02. Guarantee of orderliness

jvm-02. Guarantee of orderliness

2022-06-23 05:56:00 CaptainCats

Order guarantees

Hardware level order guarantee

Instruction rearrangement improves operation efficiency , But it also brings about the problem of inconsistent execution data ,
How to ensure order at the hardware level ?

CPU Memory barrier

Write barriers sfence
stay sfence The write operation before the instruction must be in sfence Before the subsequent write operation

Reading barrier lfence
stay lfence The read operation before the instruction must be in lfence Before the read operation after

Hybrid barrier mfence
stay mfence The read / write operation before the instruction must be in mfence Before the subsequent read / write operation

Instructions before and after the barrier cannot be rearranged , This is a CPU Level memory barrier .

Atomic directive

x86 Upper "lock" Instructions ,lock…doSth…lock It's an instruction ,
lock Followed by other instructions ,
During the execution of this instruction , This memory cannot be modified by other instructions , To ensure the order of execution .

Jvm Memory barrier

Jvm Software level , Its memory barrier depends on hardware ,
It combines reading and writing in pairs , Four memory barriers are formed :

LoadLoad barrier
For statements like this Load1;LoadLoad;load2;
stay Load2 And before subsequent read operations , Make sure that Load1 The data to be read is read .

StoreStore barrier
For statements like this Store1;StoreStore;Store2;
stay Store2 And subsequent write operations before execution , Make sure that Store1 Is visible to other processors .

LoadStore barrier
For statements like this Load1;LoadStore;Store2;
stay Store2 And subsequent write operations before execution , Make sure that Load1 The data to be read is read .

StoreLoad barrier
For statements like this Store1;StoreLoad;load2;
stay load2 And before subsequent read operations , Make sure that Store1 Is visible to other processors .

Volatile

stay jvm At the implementation level of ,volatile The read and write of the memory area are shielded :
In the face of volatile The write operation of the modified variable is preceded by StoreStore barrier , I added StoreLoad barrier ,
In the face of volatile The read operation of the modified variable is preceded by LoadLoad barrier , I added LoadStore barrier .

Synchronized

Synchronized The corresponding is C and C++ Called the synchronization mechanism provided by the operating system ,
Depending on the hardware CPU, stay CPU The level is to use lock Instructions to achieve .

原网站

版权声明
本文为[CaptainCats]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230419071037.html