The goal of the memory model is to define the access rules for each variable in the program, that is, the underlying details of the variables (including instance fields, static fields, and elements that make up the array object, excluding local variables and method parameters, because the latter is thread-private) stored in the virtual machine, and the variables are taken out of memory.
The Java memory model specifies that all variables are stored in memory, that each thread has its own working memory, that the working memory holds the variables used by the thread and the copy of the main memory, and that all operations on the variable must be made in working memory and not directly read and written to the main memory variables. There is no direct access to variables in the other's working memory between different threads, and the transfer of variable values between threads needs to be done through main memory.
Keyword volatile can be said to be the most lightweight synchronization mechanism provided by a Java virtual machine.
Two types of features:
I. Guarantee the visibility of this variable to all threads (meaning that a thread modifies the value of this variable, and the new value is immediately known to other threads)
But the operation of the volatile variable is as insecure as it is in concurrency, because the operation in Java is not atomic, even if the self-increment operation is i++, it is composed of 4 bytecode instructions.
In the scenario below, the atomicity is still guaranteed by locking (using atomic classes in synchronized or java.util.concurrent).
1. The result of the operation does not depend on the current value of the variable, or can ensure that only a single thread modifies the value of the variable
2. Variables do not need to participate in invariant constraints with other state variables
Two. Prohibit order reordering optimization, ordinary variables only guarantee that in the execution of the method, all dependent on the results of the assignment can get the correct results, and not guarantee the variable assignment of the order of operations and the Order of the program code, this is "line range expression as serial semantics" (such as int a=1 int b=a int c = 1,b depends on the value of a, so it can only run after a assignment, but C does not depend on other variables, so it runs before or after the assignment of A or B is possible.
If the scenario requires a wider range of atomicity guarantees, the memory model provides lock and unlock operations to meet this requirement, although the virtual machine does not open the lock and unlock operations directly to the user, But it provides a higher level bytecode directive Monitorenter and monitorexit to implicitly use these two operations, corresponding to the Java code is the synchronization block, synchronized keyword.
Java Thread angle memory model and volatile type variable