One, Java memory model
The Java memory model divides the internal Java virtual machine into lines stacks and heaps
The following illustration shows the call stack and local variables are stored on the thread stack, and the objects are stored on the heap.
= = ""
A local variable may be of the original type , in which case it always "stays" on the thread stack .
A local variable can also be a reference to an object. In this case, the reference (the local variable) is stored on the thread stack, but the object itself is stored on the heap .
An object may contain methods that may contain local variables . These local variables are stored on the thread stack, even if the objects they belong to are stored on the heap.
the member variables of an object may be stored on the heap with the object itself. Whether this member variable is an original type or a reference type.
static member variables follow the class definition and are also stored on the heap .
Objects stored on the heap can be accessed by all threads that hold references to the object. When a thread can access an object, it can also access the member variables of the object. If two threads invoke the same method on the same object at the same time, they will all access the member variables (shares) of the object, but each thread has a private copy of the local variables within the method.
Second, the computer hardware memory model
Iii. bridging between the Java memory model and the Hardware memory architecture
There is a difference between the Java memory model and the hardware memory schema. The hardware memory schema does not differentiate between line stacks and heap. For hardware, all line stacks and heaps are distributed in the main. Partial-line stacks and heaps may sometimes appear in the CPU cache and in registers inside the CPU.
When objects and variables are stored in various memory areas of the computer, some specific problems may arise. The main two aspects are as follows:
- Thread-to-shared variable modification visibility = " shared variable plus volatile keyword
- When reading, writing, and checking shared variables, race conditions = " synchronous resolution, the synchronization block can also ensure that all the accessed variables in the code block will be read from main memory, when the thread exits the synchronization code block, all the updated variables will be flushed back to main memory, Regardless of whether the variable is declared volatile.
Java memory Model--Learning notes