1. Definition
Java
1 keyword / modifier in.
Guaranteed to be volatile
modified shared variable visibility & orderly , but does not guarantee atomicity
3. Specific description
Below, I will explain in detail volatile
how to ensure that "the shared variable visibility & orderly , but does not guarantee atomicity" of specific principles
Reserve knowledge: atomicity, visibility & order
3.1 Ensure visibility
- The specific description of the
volatile
modified attribute ensures that the latest value can be read every time it is read. But will not & cannot update the value that has been read
- Principle
The shared attribute value modified by thread A in the working memory will be immediately refreshed to the main memory , and each time thread B / C / D reads and writes the fence to achieve similar to reading the attribute value directly from the main memory
- It's just similar, some online reads and writes that volatile-modified variables read and write directly in main memory, this statement is wrong, just show similar behavior
- The read-write fence is a CPU instruction; insert a read-write fence = tells the CPU & compiler that it must be executed before this command, and then executed after this command (ordered)
- Another function of the read-write fence is to force a cache update for different CPUs. For example, a write fence will refresh the data written before this fence to the cache to ensure visibility
3.2 Ensure order
-
Detailed description
When performing read / write operations on volatile-modified attributes, the preceding code must have been executed & the result is visible to subsequent operations -
Principle When
reordering,volatile
the read / write operation code that modifies the attribute is the dividing line . The code before the read / write operation is not allowed to be sorted to the back, and the same is not allowed to be sorted to the front. Orderly
3.3 No guarantee of atomicity
- Detailed description of
volatile
the modified attribute if the value read in before the modification, the modified, can not change the value of the work has been copied into memory. I.e. cannot prevent concurrency
- principle
// 变量a 被volatile修饰
volatile static int a=0; a++; // 包含了2步操作:1 = 读取a、2= 执行a+1 & 将a+1结果赋值给a // 设:线程A、B同时执行以下语句,线程A执行完第1步后被挂起、线程B执行了a++,那么主存中a的值为1 // 但线程A的工作内存中还是0,由于线程A之前已读取了a的值 = 0,执行a++后再次将a的值刷新到主存 = 1 // 即 a++执行了2次,但2次都是从0变为1,故a的值最终为1
4. Application scenarios
Due to the volatile
guarantee of visibility and order, the volatile
modified shared attributes generally have no problem in concurrent read / write, which can be regarded as a lightweight synchronized
implementation.
For synchronized
the specific explanation, please see the article: Java: This is a comprehensive & detailed Synchronized keyword learning guide
5. Summary
- This article explains
Java
thevolatile
keyword, whose role is to ensure visibility & ordering "shared variables , specifically summarized as follows: