Click to enter _ more _java thousand ask
1. What is the use of volatile keywords
Volatile is a keyword in the Java language and is a variable modifier. It is designed to modify variables that are accessed and modified by different threads.
The role of volatile is to ensure that this directive is not optimized by the compiler as an instruction keyword, and that all threads applied to read the variable have the same value.
Simply put, the compiler is prevented from optimizing the code, forcing all threads to read the variable from shared memory (instead of reading the backup in the register), and forcing the variable to be stored in shared memory when it changes.
The Java memory model requires the following rules: Atomicity (atomicity), Visibility (Visibility), and sortable (ordering).
Variables modified with volatile will have visibility and do not allow internal caching and reordering of threads, but it cannot make variables atomic.
Learn about the Java memory model look here: What is the Java memory model
In the current era of multi-threaded use, it is not recommended to use this low-reliability, and the developer or the scenario requires a high level of multi-threaded operation, because volatile is easy to be misused for atomic operations, if used improperly will be wrong frequency.
Java thousand ask _03 Basic grammar (014) _volatile keyword What's the use