In the Java garbage collection article, the allocation of memory at runtime of the JVM is described. One of the memory areas is the JVM virtual machine stack, and each thread runs with a line stacks,
Line stacks saves the variable value information when the thread runs. When a thread accesses an object, the value of the variable that corresponds to the heap memory is first found by the object's reference, and then the heap memory
The specific value of the variable is load into the thread's local memory, a copy of the variable is created, and then the thread is no longer related to the object in the heap memory variable value, but directly modifies the value of the replica variable.
At some point after the modification (before the thread exits), the value of the thread variable copy is automatically written back to the object in the heap variable. This changes the value of the object in the heap. Here is a picture
Describes this write interaction.
EAD and load copy variables from main memory to current working RAM
Use and assign execute code, change shared variable value
Store and write refresh main memory related content with work-in-RAM data
Where use and assign can appear multiple times
However, these operations are not atomic, that is, after read load, if the main memory count variable is modified, the value in the thread's working memory will not change because it has been loaded, so the computed result will not be the same as expected
For volatile-modified variables, the JVM virtual machine simply guarantees that the value from main memory load to the working memory of the thread is up-to-date
For example, if thread 1, thread 2 in the read,load operation, found that the value of count in main memory is 5, then the latest value will be loaded
After the thread 1 heap count is modified, it is write to main memory, and the count variable in main memory becomes 6
Thread 2 because the read,load operation has been performed, after the operation, the main memory will also be updated count of the variable value of 6
When two threads are modified with the volatile keyword in a timely manner, there is still a concurrency situation.
JVM Threading Work Understanding