Reference Blog
JVM understanding is not difficult!
Memory Area division of the JVM
Java garbage collection mechanism
JVM Memory Area
Since Java programs are executed by the JVM, we are talking about the partitioning of the Java memory area in fact the JVM memory area. Before discussing the JVM memory zoning, take a look at the process that the Java program executes:
As shown, first the Java source code file (. java suffix) is compiled by the Java compiler into a bytecode file (. class suffix), and then the class loader in the JVM loads the bytecode files for each class, and after loading, it is done by the JVM execution engine. Throughout the execution of the program, the JVM uses a space to store the data and related information that is needed during the execution of the program, which is generally referred to as the runtime data area (the run-time datacenter), which is what we often call JVM memory. So the memory management we often talk about in Java is about managing this space (how to allocate and reclaim memory space).
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. The JVM runtime data area is as follows:
As shown, the runtime data area in the JVM should include these parts. Although it is stipulated in the JVM specification that the data area should include these parts when the program is run during execution, the different virtual machine vendors can have different implementations as to how the implementation is not specified.
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.
Java Virtual Machine stack
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.
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.
Note the two exceptions that can occur in this area: one is Stackoverflowerror, and this exception is thrown when the current thread requests a stack depth that is greater than the depth allowed by the virtual machine. Making this exception is simple: recursive a function over and over again, and end up with stack overflow errors (stackoverflowerror). Another exception is the OutOfMemoryError exception, when the virtual machine stack can be dynamically extended (most of the current virtual machine can be), if you cannot request enough memory will throw OutOfMemoryError, how to make a virtual machine stack oom, refer to the code:
publicvoidstackLeakByThread(){ while(true){ new Thread(){ publicvoidrun(){ while(true){ } } }.start() }}
Local method Stack
The local method stack is very similar to the virtual machine stack, and the difference is that the virtual machine stack serves the Java code method, and the local method stack serves the native method. As with the virtual machine stack, the local method stack throws Stackoverflowerror and OutOfMemoryError exceptions. 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.
Java heap
The Java heap can be said to be the largest chunk of memory in a virtual machine. It is the area of memory shared by all threads , and almost all instance objects are stored in this area. Of course, with the development of the JIT (just in time, instant compilation technology) compiler, all objects are allocated on the heap gradually becoming less "absolute".
The Java heap is the primary area of garbage collector management. Since the collector is basically a generational collection algorithm, all Java heaps can be subdivided into: the new generation and the old age. In detail, the new generation is divided into: Eden Space, from Survivor space, to survivor space. The OutOfMemoryError exception is thrown when the heap can no longer be expanded.
Method area
The method area is also a very important area in the JVM, where information about each class is stored (including the name of the class, method information, field information), static variables, constants, compiler-compiled code, and so on. It's like a heap, it's a thread-shared area, and it's easy to understand that when we write Java code, we can access static variable objects of the same class at each line level.
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.
Similarly, OutOfMemoryError are thrown when the method area does not meet the memory allocation requirements. The Manufacturing method area memory Overflow, note, must be in JDK1.6 and previous versions before the method area overflow, the reason behind the explanation, before execution, you can put the parameters of the virtual machine-xxpermsize and-xx:maxpermsize limit the method area size.
List<String> list =new ArrayList<String>();int i =0;while(true){
The Java.lang.OutOfMemoryError:PermGen space exception is thrown after running. Explain that the intern () function of string is placed into a constant pool if the current string does not exist in the constant pool. The above code constantly adds strings to the constant pool, which will eventually result in out-of-memory, throwing an oom in the method area.
The following explains why the above code must be run before JDK1.6. As we mentioned earlier, after JDK1.7, the constant pool is put into the heap space, which causes the function of the intern () function to be different, how to vary the method, and look at the following code:
String str1 =new StringBuilder("hua").append("chao").toString();System.out.println(str1.intern()==str1);String str2=new StringBuilder("ja").append("va").toString();System.out.println(str2.intern()==str2);
This code is different from the results of the JDK1.6 and JDK1.7 runs. JDK1.6 result is: False,false, JDK1.7 The result is true, false. The reason is: JDK1.6, the Intern () method will be the first time a string instance encountered is copied into a constant pool, and a reference to the string in the constant pool is returned, and the string instance created by StringBuilder is above the heap, so it is not necessarily the same reference and returns FALSE. In JDK1.7, intern no longer replicates the instance, only the reference to the first occurrence of the instance is saved in the constant pool, so the reference returned by intern () and the string instance created by StringBuilder are the same. Why is the comparison returned to str2 false? This is because when the class is loaded internally in the JVM, there is already a string of "Java" that does not conform to the "first occurrence" principle and therefore returns false.
Garbage collection (GC)
In the garbage collection mechanism of the JVM, judging whether an object is dead or not, it is not based on whether or not the object has references to it, but through accessibility analysis. References between objects can be abstracted into a tree structure, with root (GC Roots) as a starting point, searching from these roots, searching through the chain called the reference chain, when an object to the GC Roots no reference chain connected, it proves that this object is not available, It is important to note, however, that objects that are judged unreachable do not necessarily become recyclable objects. An object that is judged unreachable must undergo at least two marking processes to become a recoverable object, and if it is still not possible to escape from being a recyclable object during these two marks, it is essentially a recyclable object.
What about those objects that can be used as GC roots? There are mainly the following types:
1. The object referenced in the virtual machine stack (local variable table in the stack frame).
2. The object referenced by the class static property in the method area.
3. Objects referenced by constants in the method area
4. The object referenced by the JNI (that is, the generally said native method) in the local method stack.
In addition, Java provides soft and weak references, and soft references are recycled when the JVM has insufficient memory, and soft references are used when possible to preserve the object, while the weak reference type is the object that is reclaimed regardless of whether the JVM memory is sufficient. Weak references use when you want to release the object as much as possible, and we will make some objects that compare memory but may be used later, such as bitmap objects, which can be declared as soft references, and for the activity referenced in handle, we want to handler to release it as much as possible. So you can declare it as a weak reference. Note, however, that each time you use this object, you need to indicate whether it is null to avoid errors.
Here are three common examples to summarize the more common cases where objects are judged to be recyclable:
-To assign a reference to null or to point a reference to an object to a new object, such as the following code:
newnullnewnew Object();obj1 = obj2;
- The object that the local reference points to, such as the following code:
void fun() {..... for(int i=0;i<10;i++) { new Object(); System.out.println(obj.getClass()); } }
Each time the loop finishes executing, the resulting object object becomes a recyclable object.
-only weak references to objects associated with them, such as:
new WeakReference<String>(new String("world"));
Three common garbage collection algorithms
After determining which garbage can be recycled, what the garbage collector has to do is start a garbage collection, but there is one problem: how to effectively recycle. Because the Java Virtual Machine specification does not explicitly stipulate how to implement a garbage collector, each vendor's virtual machine can implement a garbage collector in different ways, so it is only a discussion of the core ideas of several common garbage collection algorithms.
-Tag-Clear algorithm
First, through the accessibility analysis of the recyclable objects tagged, and then the unified collection of all tagged objects, marking process is actually the process of accessibility analysis. There are 2 deficiencies in this approach: efficiency issues, the efficiency of labeling and clearing two processes is not high, and the other is the spatial problem, which results in a large amount of discontinuous memory fragmentation after the mark is cleared. Too many fragments can cause the subsequent process to allocate space for large objects without finding enough space to trigger a new garbage collection action ahead of time.
- Replication Algorithms
To solve the efficiency problem, the replication algorithm divides the memory into two blocks of the same size, using only one piece at a time. When this memory is exhausted, the surviving object is copied to the other memory. Then clean up the memory that has been used once. This makes it possible to recycle only half of the area at a time, and memory allocations are not considered memory fragmentation.
However, the cost is unacceptable and requires half of the memory space to be sacrificed. Obviously, the efficiency of the copying algorithm is very much related to the number of surviving objects, if there are many surviving objects, then the efficiency of the copying algorithm will be greatly reduced.
-Labeling-sorting algorithms
The tagging algorithm is simple to mark objects that need to be recycled, and after the token is finished, it does not clean recyclable objects directly, but instead moves the surviving objects to one end and cleans up memory outside the end boundary. The exact process is as follows:
- Generational collection Algorithms
The generational collection algorithm is the algorithm used by most of the JVM's garbage collectors today. Its core idea is to divide the memory into several different regions based on the life cycle of the object's survival. In general, the heap zoning is divided into the old age (tenured Generation) and the New Generation (young Generation), the characteristics of the old age is that each garbage collection only a small number of objects need to be recycled, and the new generation is characterized by a large number of objects to be recycled each time the garbage collected, Then we can take the most suitable collection algorithm according to the characteristics of different generations.
At present, most of the garbage collector for the new generation of the replication (Copying) algorithm , because each garbage collection in the Cenozoic to recover most of the objects, that is, the number of operations need to replicate less, but the actual is not in accordance with the proportion of 1:1 to divide the new generation of space, In general, the Cenozoic is divided into a larger Eden space and two smaller Survivor spaces with a default scale of eden:survivor=8:1. This is how the Cenozoic regions are divided, each time an instance is allocated in Eden and a piece of survivor, and when recycled, the surviving object is copied to the remaining survivor. Only 10% of the memory is wasted, but the efficiency is high. When the rest of the survivor memory is insufficient, you can go to the old memory allocation guarantee. How to understand the allocation of security, in fact, when the memory is not enough, to the old memory space allocation, and then wait for the new generation of memory slowed down, the memory back to the old age, to maintain the eden:survivor=8:1 in the Cenozoic. In addition, two Survivor have their own name: from Survivor, to Survivor. The identities are often swapped, that is, sometimes this memory is allocated with Eden, sometimes in another. Because they often replicate with each other.
Because of the characteristics of the old age is to recover only a small number of objects each time, the general use is the mark-finishing (mark-compact) algorithm .
Note that there is another generation outside the heap that is the permanent generation (permanet Generation), which is used to store class classes, constants, method descriptions, and so on. The recovery of the permanent generation mainly recycles two parts: obsolete constants and useless classes.
Class loading mechanism
Class from being loaded into virtual machine memory, to unloading out of memory, the entire lifecycle includes: load, validate, prepare, parse, initialize, use, and unload seven phases.
The order in which the 5 phases are loaded, validated, prepared, initialized, and unloaded is determined. The parsing phase is not necessarily: it can be started after the initialization phase in some cases, in order to support Java runtime bindings.
In the implementation specification of the JVM, the "active use" virtual machine of all classes is executed to initialize the corresponding class, so the problem boils down to the meaning of "active use".
-Create an instance of the class. Object A = new ClassA ();
-Access static variables of a class or interface or assign values to static variables;
-the static method of invoking the class;
-use reflection mechanism;
-When initializing a subclass of a class, the parent class is also actively used;
-Start class.
It is also important to note that using subclasses to refer to the static fields of the parent class does not cause subclasses to initialize:
Public class superclass{ Public Static intValue=123;Static{System.out.printLn ("Superclass init!"); }} Public class subclass extends superclass{ Static{System.out.println ("Subclass init!"); }} Public class Test{ Public Static void Main(string[] args) {System.out.println (subclass.value); }}//output//superclass init!
For static variables, only classes that directly define the field are initialized, so referencing a static variable defined in the parent class by a subclass class will only trigger the parent class to initialize without triggering the subclass initialization.
Referencing a class through an array definition does not trigger initialization of this class:
publicclass Test{ publicstaticvoidmain(String[] args){ SuperClass[] sca=new SuperClass[10]; }}
Constants are stored in the caller's constant pool at compile time and are not directly referenced to the class that defines the constants, so class initialization that defines the constants is not triggered, and the sample code is as follows:
public class constclass { public static final String hello_world= "HELLO World" ; static {System.out.println ( "Constclass init!" ); }}public class Span class= "Hljs-title" >test { public Static void main (string[] args) {SYSTEM.O Ut.print (Constclass.hello_world); }}//above code does not appear constclass init!
Load
Class loading refers to reading the binary hand in the class's. class file into memory, placing it in the method area of the run-time data area, and then creating a Java.lang.Class object in the heap to encapsulate the data structure of the class within the method.
So the loading process mainly does the following 3 things
-Get the binary stream of this class through the fully qualified name of a class
-Convert the static storage structure represented by this byte stream into the run-time data structure of the method area
-Generate a Java.lang.Class object representing this class in memory as a variety of data access portals for the class of the method area.
Verify
This phase is primarily to ensure that the class file byte stream contains information that meets the requirements of the current virtual machine and does not compromise the security of the virtual machine itself.
Get ready
The prep phase is a phase that formally allocates memory for class variables and sets the initial value of class variables, and the memory used by these variables is allocated in the method area. First, allocating memory at this time only includes class variables (variables that are modified by static), not instance variables. Instance variables are allocated in the Java heap along with the objects as they are instantiated. Second, the initial value "typically" is a 0 value of the data type, assuming that a class variable is defined as
publicstaticint value=123;
The initial value of the variable value after the prep phase is 0, not 123, because no Java method has been executed, and value assignment 123 is stored in the class constructor Clinit () method after the program is compiled.
Analytical
The parsing phase is the process of replacing the symbolic reference of a constant pool in a virtual machine with a direct reference.
Initialization
Class initialization is the last step in class loading, and the rest of the actions are virtual machine-driven and controlled in addition to the load phase in which the user can participate through the custom ClassLoader. In the initialization phase, the Java program code is defined in the actual execution class.
During the preparation phase, variables have already been assigned the initial value of the system requirements, and during the initialization phase, class variables are initialized according to the subjective plan developed by the programmer through the program. The initialization process is actually the process of executing the class constructor Clinit () method.
The Clinit () method is generated by the compiler's automatic collection of assignment actions for all class variables in the class and statements in the static statement block. The order of collection is in the order in which the statements appear in the source file. A static statement block can only access variables defined before a static statement block, and variables defined after it may be assigned values, but cannot be accessed. As shown below:
publicclass Test{ static{ i=0;//給变量赋值,可以通过编译 System.out.print(i);//这句编译器会提示:“非法向前引用” } staticint i=1;}
The Clinit () method differs from the class constructor (or instance constructor init ()) in that he does not need to explicitly call the parent class constructor, and the virtual opportunity guarantees that the clinit () of the parent class is executed before the Clinit () method of the subclass executes.
JVM Overview of Java Learning summary