Java memory Model
What is the Java memory model
The Java Virtual Machine specification attempts to define a Java memory model (MODEL,JMM) that masks the access differences of various hardware and operating systems to allow Java programs to achieve consistent memory access across various platforms. Prior to this, mainstream programming languages (such as C + +, etc.) directly use the physical hardware and operating system's memory model, therefore, due to differences in memory models on different platforms, it is possible to cause the program to be completely normal on a set of platforms, while concurrent access on another set of platforms is often error- Therefore, it is not allowed to write programs for different platforms under certain scenarios.
The Java memory model needs to be sufficiently rigorous to make Java's concurrent memory access operations ambiguous, and the Java memory model must be loosely defined enough to allow the virtual machine's implementation to have enough free space to take advantage of the various features of the hardware to get better execution speed.
Main memory and working memory
The main purpose of the Java memory model is to define the access rules for each variable in the program, that is, the underlying details of storing variables in the virtual machine into memory and removing variables from memory. Note that the variables here do not include local variables and method parameters, because they are thread-private, are not shared, and naturally there is no competition, and the variables here should be instance fields, static fields, and elements that make up the array object.
Inter-memory interaction
With regard to the specific interaction protocol between main and working memory, i.e. how a variable is copied from the main memory to the working memory, how to synchronize from the working memory back to the main memory, the following 8 operations are defined in the Java memory model, and the virtual machine implementation must ensure that each operation of the following volume is atomic, Not to be divided:
1. Lock (Lock): A variable acting on the main memory, which identifies a variable as a thread-exclusive state
2. Unlock (Unlocked): A variable that acts on the main memory, releasing a variable that is in a locked state, and the released variable can be locked by another thread
3. READ: A variable acting on the main memory that transfers the value of a variable from main memory to the working memory of the thread for subsequent load actions to use
4. Load (load): A variable that acts on the working memory, which puts the value of a read operation from the main memory into a variable copy of the working memory
5, use: The variable that acts on the working memory, it passes the value of a variable in the working memory to the execution engine, and does this when the virtual opportunity is to a bytecode instruction that needs to use the value of the variable.
6. Assign (Assignment): A variable in the working memory that assigns a value received from the execution engine to a variable in the working memory, which is performed whenever the virtual opportunity is assigned to a byte-code instruction that assigns a value to a variable.
7. Store: A variable in working memory that transfers the value of a variable in the working memory to main memory for subsequent write operations to use
8. Write (write): A variable that acts on the main memory, which puts the store operation from the value of the variable in the working memory into the variable of the main memory
The Java memory model also specifies that the following rules must be met when performing the 8 basic operations described above:
1. One of the read and load, store, and write operations is not allowed to appear separately
2, does not allow a thread to discard its most recent assign operation, that is, the variable in the working memory changes the lag must synchronize the change back to the main memory
3. One thread is not allowed to synchronize data from the working memory of the thread back to main memory for no reason
4, a new variable can only be born from the main memory, not allowed in working memory directly using a non-initialized (load or assign) variable
5. A variable is allowed only one thread to lock it at the same time, but the lock operation can be repeated multiple times by the same thread, and after executing lock multiple times, the variable will be unlocked only if the same number of unlock operations are performed .
6. If you perform a lock operation on the same variable, it will empty the value of this variable in the working memory and need to re-execute the value of the load or assign operation initialization variable before the execution engine uses the variable .
7, if a variable is not locked by the lock operation beforehand, it is not allowed to unlock operation, nor allow to unlock a variable locked by another thread
8. before performing a unlock operation on a variable, you must first synchronize this variable back into main memory
special rules for volatile variables
Keyword volatile can be said to be the most lightweight synchronization mechanism provided by a Java virtual machine.
Once a variable is defined as volatile, it will have two features:
1, to ensure that this variable "visibility" of all threads, the so-called "visibility" refers to when a thread modifies the value of this variable, the new value for other threads can be immediately known, and ordinary variables do not do this, the value of the normal variable in the thread between the transfer of the main memory to complete, For action on the volatile keyword, see the volatile keyword usage example, and again,volatile only guarantees visibility and does not guarantee that operations based on volatile variables are sent off safely.
2. the second semantics of using volatile variables is to prohibit command reordering optimizations , and ordinary variables will only guarantee that the correct results will be obtained in the execution of the method in all places that depend on the result of the assignment, without guaranteeing that the order of the variable assignment is consistent with the order of execution in the program code.
Summarize the special rules defined by the Java memory model for volatile variables:
1. In working memory, each time a variable is used, the line must be refreshed with the latest value from main memory to ensure that the value of the changes made by other threads to the variable can be seen
2. In working memory, each time a variable is modified, it must be immediately synchronized back to main memory to ensure that other threads can see their own modifications to the variable
3, volatile modified variables are not ordered to re-order optimization, to ensure that the code is executed in the same order as the program
Java memory model
According to the Java Virtual Machine specification, the runtime data area typically includes these parts: program Counter Register, Java stack (VM stack), local method Stack (Native), method area ( Method area), heap.
1. Program Counter
Program Counter Register, also known as PC Register. Must have learned assembly language friend to program counter this concept is not unfamiliar, in assembly language, the program counter refers to the register in the CPU, it is stored in the program is the current execution of the instruction address (also can be said to save the next instruction where the address of the storage unit), when the CPU needs to execute instructions, You need to get the address of the storage unit of the instruction that is currently required to execute from the program counter, and then obtain the instruction according to the obtained address, and after the instruction is obtained, the program counter automatically adds 1 or the address of the next instruction according to the transfer pointer, so it loops until all instructions are executed.
Although the program counters in the JVM are not the same as the CPU registers in the physical concept as the program counters in assembly language, the function of the program counter in the JVM is logically equivalent to the function of the program counter in assembly language, that is to say which instruction is executed.
Because in the JVM, multithreading is to get CPU execution time by rotating threads, so at any given moment, a CPU kernel only executes instructions in one thread, therefore, in order to be able to make each thread switch back to the program execution location before switching, Each thread needs to have its own independent program counter, and cannot be interfered with each other, otherwise it will affect the normal order of execution of the program. So, so to speak, the program counters are private to each thread.
In the JVM specification, if a thread executes a non-native method, the program counter holds the address of the instruction that is currently required to execute, and if the thread executes the native method, the value in the program counter is undefined.
Because the size of the space that is stored in the program counter does not change with the execution of the program, there is no memory overflow phenomenon (OutOfMemory) for program counters.
2.Java Stack
The Java stack, also known as the VM stack (Java vitual machine stack), is what we often call a stack, similar to a stack in a C-language data segment. In fact, the Java stack is the memory model that the Java method executes. Why do you say that? Let's explain why.
In the Java stack is a stack of frames, each stack frame corresponding to a called method, in the stack frame including the local variable table (local Variables), the operand stack (Operand stack), A reference to the run-time pool of the class to which the current method belongs (the concept of running a constant pool is discussed in the method area section), the Reference to runtime constant pool, the return address of the method, and some additional additional information. When a thread executes a method, it creates a corresponding stack frame and pushes the stack frame to be built. When the method finishes executing, the stack frame is stacked. Therefore, the stack frame corresponding to the method that the thread is currently executing must be at the top of the Java stack. In this case, you should understand why the use of recursive methods can easily lead to stack memory overflow phenomenon and why the space of the stack does not have to be managed by the programmer (in Java, of course, the programmer is basically not related to memory allocation and release of things, because Java has its own garbage collection mechanism), This part of the space allocation and release are automatically implemented by the system. For all programming languages, this part of the stack is opaque to programmers. Represents a model of a Java stack:
Local variable table, as the name implies, must not explain that we should understand its role. is used to store local variables in the method (including non-static variables declared in the method and function parameters). For a variable of the base data type, the value is stored directly, and for a variable of the reference type, a reference to the object is saved. The size of the local variable table can be determined by the compiler, so the size of the local variable table will not change during program execution.
Operand stack, must have learned the data structure of the stack of friends presumably to the expression evaluation problem is not unfamiliar, the most typical application of the stack is used to evaluate the expression. When you think about a thread executing a method, it is actually the process of executing the statement, and in the final analysis it is the process of calculating. So you can say that all the computational processes in the program are done with the help of the operand stack.
A reference to a run-time pool, because a constant in the class is likely to be used during the execution of the method, so a reference must be directed to the run-time.
method returns an address that must be saved in the stack frame when a method is executed to return to the place where it was previously called.
Because the methods that each thread is executing may be different, each thread will have its own Java stack that does not interfere with each other.
3. Local Method Stack
The local method stack works very much like the Java stack. The difference is simply that the Java stack is for the Java Method service, while the local method stack serves the local method (Native). In the JVM specification, the specific implementation method and data structure of local development are not enforced, and the virtual machine is free to implement it. The local method stack and the Java stack are directly merged into the hotsopt virtual machine.
4. Heap
In the C language, this part of the heap is the only area of memory that a programmer can manage. Programmers can use the malloc function and the free function to apply and release space on the heap. So what's it like in Java?
The heap in Java is used to store the object itself as well as an array (of course, the array references are stored in the Java stack). But unlike in the C language, in Java, programmers do not have to care about the issue of space release, Java garbage collection mechanism will be automatically processed. So this part of the space is also the main area of Java garbage collector management. In addition, the heap is shared by all threads, and there is only one heap in the JVM.
5. Method area
The method area is also a very important area in the JVM, which, like the heap, is a thread-shared area. In the method area, information is stored for each class (including the name of the class, method information, field information), static variables, constants, and compiler-compiled code.
In the class file, in addition to the description of the fields, methods, interfaces, and so on, there is a constant pool that stores the literal and symbolic references generated during compilation.
A very important part of the method area is the run-time pool, which is the runtime representation of the constant pool of each class or interface, which is created when classes and interfaces are loaded into the JVM. Of course, not the contents of the class file constant pool can enter the run-time pool, and the new constants can be placed in the run constant pool during runtime, such as The Intern method of string.
In the JVM specification, there is no mandatory requirement for the method area to implement garbage collection. Many people are accustomed to calling the method area "permanent generation" because the hotspot virtual machine implements the method area as a permanent generation, so that the JVM's garbage collector can manage this part of the area as if it were managed by the heap, eliminating the need to specifically design a garbage collection mechanism for this part. Since JDK7, however, the hotspot virtual machine has removed the run-time constant pool from the permanent generation.
Java memory model