Java Memory Model and garbage collection, java model garbage collection
1. Java Memory Model
When executing a program, the Java Virtual Machine divides the memory it manages into several data regions. The distribution of these data regions is shown in:
- Program counter: A small memory area that points to the byte code currently executed. If the thread is executing a Java method, this counter records the address of the Virtual Machine bytecode instruction being executed. If the Native method is executed, this calculator value is blank.
- Java Virtual Machine Stack: the life cycle of a private thread is the same as that of a thread. A stack frame is created during each method execution to store information such as the local variable table, operand stack, dynamic link, and method exit.
- Local method Stack: similar to the VM stack function, the VM stack executes Java method services for the VM, while the local method stack serves the Native method used.
- Java heap: it is the largest part of the VM management memory and is shared by all threads. This region is used to store object instances, and almost all objects are allocated in this region. Java heap is the main area for memory collection. From the perspective of memory collection, most collectors currently use generational collection algorithms, so Java heap can be subdivided into the new generation and old generation, further subdivision can be divided into Eden space, From other vor space, To other vor space. According to Java Virtual Machine specifications, Java heap can be physically discontinuous, as long as the logic is continuous.
- Method Area: similar to Java, it is shared by various threads and used to store data such as class information, always bright, static variables, and Code Compiled by the real-time compiler.
- The runtime constant pool is a part of the Method Area. In addition to the Class version, field, method, interface, and other description information, the Class file, another information is the constant pool, which is used to store various literal quantities and symbol references generated during the compilation period. During running, new constants can be placed in the constant pool. The commonly used intern () method of the String class is used. When a String instance calls intern, java checks whether the constant pool has the same Unicode String constant. If yes, it returns its reference. If no, in the constant pool, add a Unicode value equal to the instance string and return its reference.
2. How to Determine the spam object
Java heap stores several object instances. Before the Garbage Collector recycles the heap, it must first determine which objects are "alive" and which are "dead ", that is, objects that are not used by any means.
Reference COUNTING METHOD
The reference counting method is simple and efficient. It is a good algorithm in most cases. The principle is: Add a reference counter to the object. Every time a reference is made to the object, the counter is incremented by 1. When the reference fails, the counter is reduced by 1, when the counter value is 0, the object is no longer used. It should be noted that the reference counting method is difficult to solve the issue of circular reference between objects. Mainstream Java virtual machines do not use the reference counting method to manage memory.
Accessibility Analysis Algorithm
The basic idea of this algorithm is to use a series of objects called "GC Roots" as the starting point and start to search down from these nodes. The paths searched through are referred to as Reference chains ), when an object to GC Roots is not connected by any reference chain (in graph theory, it is impossible to connect from GC Roots to this object), it is proved that this object is unavailable ., Although object 5, object 6, and object 7 are correlated with each other, they are not reachable to GC Roots, so they will be regarded as recyclable objects.
In Java, the following types of objects can be used as GC Roots objects:
- Objects referenced in the Virtual Machine stack (the local variable table in the stack frame.
- Objects referenced by class static attributes in the method area.
- Objects referenced by constants in the method area.
- Objects referenced by JNI (Native method) in the local method stack.
Now the problem arises. Will there be a circular reference problem between objects in the accessibility analysis algorithm? The answer is yes, that is, there will be no circular reference between objects. In addition to the object graph, GC Root is a special "Starting Point" and cannot be referenced by objects in the object graph. For more information, see http://www.zhihu.com/question/29218534.
Object survival Or death (To Die Or Not To Die)
Even the reachable objects in the accessibility analysis algorithm are not "non-dead". At this time, they are temporarily in the "suspended" stage, and an object must be declared dead, at least two marking processes are required: if the object does not have a reference chain connected to GC Roots after the Accessibility analysis, it will be marked for the first time and filtered, the filtering condition is whether it is necessary to execute the finalize () method for this object. When the object does not overwrite the finalize () method, or the finalize () method has been called by the virtual machine, the virtual machine regards both cases as "unnecessary execution ". In the program, we can overwrite finalize () for a "thrilling" self-rescue process, but this is only one chance.
/*** This Code demonstrates two points: * 1. The object can be self-saved when it is GC. * 2. there is only one chance of self-help, because the finalize () method of an object can only be automatically called once by the system * @ author zzm */public class FinalizeEscapeGC {public static FinalizeEscapeGC SAVE_HOOK = null; public void isAlive () {System. out. println ("yes, I am still alive :)") ;}@ Override protected void finalize () throws Throwable {super. finalize (); System. out. println ("finalize mehtodd executed! "); FinalizeEscapeGC. SAVE_HOOK = this;} public static void main (String [] args) throws Throwable {SAVE_HOOK = new FinalizeEscapeGC (); // the first time the object is successfully saved, SAVE_HOOK = null; System. gc (); // because the finalize method has a low priority, 0.5 seconds are paused to wait for its Thread. sleep (500); if (SAVE_HOOK! = Null) {SAVE_HOOK.isAlive ();} else {System. out. println ("no, I am dead :(") ;}// the following code is exactly the same as above, but this self-help failed SAVE_HOOK = null; System. gc (); // because the finalize method has a low priority, 0.5 seconds are paused to wait for its Thread. sleep (500); if (SAVE_HOOK! = Null) {SAVE_HOOK.isAlive ();} else {System. out. println ("no, I am dead :(");}}}
The running result is:
finalize mehtod executed! yes, i am still alive :) no, i am dead :(
Next, reference
Whether the reference count algorithm is used to determine the number of objects referenced, or the Accessibility analysis algorithm is used to determine whether the object's reference chain is reachable, it is related to "Reference" to determine whether the object is alive. Before JDK 1.2, reference definitions in Java were quite traditional: if the values stored in reference data represent the starting address of another memory, this memory represents a reference. After JDK 1.2, Java expanded the concept of Reference, which divided references into Strong Reference, Soft Reference, and Weak Reference) and Phantom Reference, which gradually weaken.
- Strong references are commonly used in program code. references such as "Object obj = new Object ()", as long as strong references still exist, the garbage collector will never recycle referenced objects.
- Soft references are used to describe some useful but not necessary objects. For soft reference associated objects, these objects will be listed in the recycle range for the second recycle before the system will encounter a memory overflow exception. If the recovery does not have enough memory, a memory overflow exception will be thrown. After JDK 1.2, the SoftReference class is provided for soft reference.
- Weak references are used to describe non-essential objects, but they are weaker than soft references. objects associated with weak references can only survive until the next garbage collection. When the spam collector is working, only objects associated with weak references will be reclaimed no matter whether the current memory is sufficient. After JDK 1.2, the WeakReference class is provided to implement weak references.
- A Virtual Reference is also called a ghost reference or phantom reference. It is the weakest reference relationship. Whether an object has a virtual reference does not affect its survival time, nor can it be used to obtain an object instance through virtual reference. The only purpose of setting a Virtual Reference Association for an object is to receive a system notification when the object is recycled by the Collector. After JDK 1.2, the PhantomReference class is provided to Implement Virtual Reference.
Soft reference example:
Package jvm; import java. lang. ref. softReference; class Node {public String msg = "";} public class Hello {public static void main (String [] args) {Node node1 = new Node (); // strongly reference node1.msg = "node1"; SoftReference <Node> node2 = new SoftReference <Node> (node1); // soft reference node2.get (). msg = "node2"; System. out. println (node1.msg); System. out. println (node2.get (). msg );}}
Output result:
node2node2
3. Typical garbage collection algorithms
1. Mark-Sweep (Mark-clear) Algorithm
This is the most basic garbage collection algorithm. The most fundamental reason is that it is the easiest to implement and the simplest to think about. The tag-clearing algorithm is divided into two phases: the tag phase and the clear phase. The task in the mark phase is to mark all objects to be recycled, and the clear phase is to recycle the space occupied by the marked objects. The specific process is shown in:
It is easy to see that the tag-clearing algorithm is easier to implement, but a serious problem is that memory fragments are easily generated, too many fragments may cause insufficient space to be found when large objects need to be allocated in the subsequent process, and a new garbage collection action will be triggered in advance.
2. Copying Algorithm
To solve the Mark-Sweep algorithm defect, the Copying algorithm is proposed. It divides the available memory into two equal-size blocks by capacity and uses only one of them at a time. When the memory of this block is used up, copy the still living objects to the other block, and then clear the used memory space, in this way, memory fragmentation is not prone. The specific process is shown in:
Although this algorithm is easy to implement and runs efficiently, it is not easy to generate memory fragments, but it imposes a high cost on the use of memory space, because the memory that can be used is halved.
Obviously, the efficiency of the Copying algorithm is significantly related to the number of surviving objects. If there are many surviving objects, the efficiency of the Copying algorithm will be greatly reduced.
3. Mark-Compact Algorithm
To solve the Copying algorithm defect and make full use of the memory space, the Mark-Compact algorithm is proposed. The algorithm Mark phase is the same as Mark-Sweep, but after the Mark is completed, it does not directly clear the recyclable object, but moves the surviving object to one end, then, the memory outside the end boundary is cleared. The specific process is shown in:
4. Generational Collection (Generational Collection) Algorithm
The generational collection algorithm is currently used by most JVM garbage collectors. Its core idea is to divide the memory into several different regions based on the lifecycle of the object. Generally, heap zoning is divided into Tenured Generation and Young Generation. In the old age, only a few objects need to be recycled during each garbage collection, the new generation is characterized by the fact that a large number of objects need to be recycled during each garbage collection, the most suitable collection algorithm can be adopted based on the characteristics of different generations.
At present, most garbage collectors adopt the Copying Algorithm for the new generation, because most objects need to be recycled in each garbage collection in the new generation, that is, the number of replication operations is small, however, in reality, the ratio of is not used to divide the space of the new generation, generally, the new generation is divided into a large Eden space and two small elastic vor spaces (generally). Each time an Eden space and one of the elastic vor spaces are used, when recycling, copy the surviving objects in Eden and vor to another vor space, and then clear the Eden and the used vor space.
In the old age, only a small number of objects are recycled each time. Generally, the Mark-Compact algorithm is used.
References
1. Chapter 2 and Chapter 3 of deep understanding of Java Virtual Machine
2. Java garbage collection mechanism
3. Java method area and runtime constant pool overflow problem analysis