The underlying principle of java volatile

introduction

  1. Variables modified by volatile in the Java language can ensure visibility in thread scenarios,
  2. Prevent the processor instruction reordering instruction rearrangement in a multithreaded environment, there will be visibility problems

That is, there is thread AB, which can access the volatile variable x.
When thread A modifies x, thread B can access the variable x again to get the latest value of x.
Non-volatile variables cannot guarantee this.

Principle of visibility

If the Volatile variable modifier is used properly, it will be cheaper to use and execute than synchronized, because it will not cause thread context switching and scheduling.

When a shared variable decorated with a volatile variable is written, lock assembly code is used. The instruction with the lock prefix will cause two things under a multi-core processor.

  1. The data of the current processor cache line will be written back to the system memory.
  2. This operation of writing back to memory will cause the data cached at the memory address in other CPUs to be invalid. (Other CPUs invalidate the cache through cache sniffing)

Principle of preventing rearrangement

  1. Insert StoreStore barrier before each volatile write operation and StoreLoad barrier after write operation
  2. Insert a LoadLoad barrier before each volatile read operation, and a LoadStore barrier after a read operation;

java memory barrier

  • Java's memory barrier is usually called the four types, namely LoadLoad, StoreStore, LoadStore, StoreLoad is actually a combination of the above two, complete a series of barriers and data synchronization functions.
  • LoadLoad barrier: For such statements Load1; LoadLoad; Load2, before the data to be read by Load2 and subsequent read operations is accessed, ensure that the data to be read by Load1 is read.
  • StoreStore barrier: For such statements Store1; StoreStore; Store2, before Store2 and subsequent write operations are performed, ensure that Store1 write operations are visible to other processors.
  • LoadStore barrier: For such statements Load1; LoadStore; Store2, before Store2 and subsequent write operations are flushed out, ensure that the data to be read by Load1 is read.
  • StoreLoad barrier: For such statements Store1; StoreLoad; Load2, before Load2 and all subsequent read operations are performed, ensure that Store1 writes are visible to all processors. Its overhead is the largest of the four barriers. In most processor implementations, this barrier is a omnipotent barrier, combining the functions of the other three memory barriers

Quote

https://www.jianshu.com/p/2ab5e3d7e510
https://www.cnblogs.com/chenssy/p/6379280.html

Published 17 original articles · won 24 · views 280,000 +

Guess you like

Origin blog.csdn.net/qq_22956867/article/details/79400428