Use the keyword Java Concurrency --volatile

Use the volatile keyword
volatile key
principles
for using the volatile keyword
if and only if all the following conditions are met, only == == should use the volatile keyword:
the role of the volatile keyword
volatile keyword
volatile keyword modifications the variable that is volatile variable, which is a weaker synchronization mechanism provided by Java, for ensuring updates to volatile variables to be able to inform other threads.

Principle
To understand the principle of the volatile keyword, you need to understand the Java Memory Model (JMM), where not start. Variable is modified using the volatile keyword, so that the amount of change can have the following two features:

Visibility variable, a thread changes to the volatile variables, other threads can be seen immediately;
that is volatile variables are not cached in the workspace thread processor or other invisible places on volatile variable changes immediately synchronized to the main memory. -: (volatile write to the rule in the face of volatile variables read this variable after the first occurrence of one of the principles in the JMM occurs first.)
Ordering the volatile keyword to limit the instruction memory barrier by increasing the rearrangement of the way, so operating compiler and JVM will not be a volatile variable reordering memory operations together with the other;
for the use of the volatile keyword case
volatile variables are often used to do a certain operation is completed, interrupted or other status symbol represented, for example in check the status of a mark to determine whether to exit loop of the case.
1
if and only if all the following conditions are met, it should use the volatile keyword:
1, writes to variables do not depend on the current value of the variable, or you can ensure that only a single thread can update the values of variables.
2, the variable will not be included along with other state variables invariance condition
3, the lock does not need to access the variable.
1
2
3
role keyword volatile
impact on the visibility of the volatile keyword is more important than the volatile variable itself, volatile keyword does not only affect the visibility of the modified variable. When a thread variable A is written to a volatile, volatile thread B to read the variable later, before writing the value of a volatile variable thread visible all the variables A, B in the read after the volatile variables are thread B visible (memory barrier).

The volatile keyword does not guarantee atomicity.
--------------------- 

Guess you like

Origin www.cnblogs.com/hyhy904/p/10942245.html
Recommended