Talking about java garbage collection mechanism, talking about java garbage collection
I. Problems
I recently encountered many questions about the garbage collection mechanism in java, so I wrote a blog to share with you what the garbage collection mechanism in java is. The so-called garbage collection even if the jvm does not think that your object is necessary to clear you out, then the problem arises.
Let me check the problem one by one.
2. How to determine whether an object needs to be recycled
First, let's look at the question: if an object is determined to be "junk "? Since the task of the garbage collector is to recycle the space occupied by the garbage objects for use by new objects, how does the Garbage Collector determine that an object is "garbage "? -The method used to determine whether an object can be recycled. Some objects need to be cleaned up due to insufficient jvm memory. The objects to be recycled in the next round will be cleared.
In java, references are used to associate objects. That is to say, to operate on objects, references must be used. Obviously, a simple method is to judge whether an object can be recycled by reference counting. Without losing its universality, if an object is not associated with any reference, it means that the object is unlikely to be used elsewhere, and the object becomes a recyclable object. This method becomes the reference notation.
This method is simple, crude, and highly efficient. High efficiency will inevitably expose some problems. If some objects are referenced cyclically, this algorithm cannot be recycled even if you assign null values to the objects. See the following code.
public class GcTest { public Object object = null; public static void main(String[] args) { GcTest gcTest1 = new GcTest(); GcTest gcTest2 = new GcTest(); gcTest1.object = gcTest1; gcTest2.object = gcTest2; gcTest1 = null; gcTest2 = null; }}
Although gcTest1 and gcTest2 are null, the objects they direct to will not be accessed, but because they reference each other, their reference count is not 0, then the Garbage Collector will never recycle them.
The above problem has been exposed. Let's take a look at how jvm solves this problem. To solve this problem, the Accessibility analysis method is adopted in Java. The basic idea of this method is to search by a series of "GC Roots" objects as the starting point. If there is no reachable path between "GC Roots" and an object, this object is not reachable, but it should be noted that the object to be judged as inaccessible may not necessarily become a recyclable object. Objects that are determined to be inaccessible must go through at least two marking processes to become recyclable objects. If the two marking processes still do not escape the possibility of becoming recyclable objects, it is basically a recyclable object. I have explained the concept of GC Roots carefully in deep understanding of jvm. If you want to know more about it, read the book I introduced.
The following three types of objects are used as GC roots in jvm to determine whether an object can be recycled (generally, we only need to know the Virtual Machine stack and static reference)
1. Objects referenced in the Virtual Machine stack (JVM stack) (frames )). We know that when each method is executed, jvm will create a corresponding stack frame (the stack frame includes the operand stack, local variable table, and reference of the runtime volume pool ), stack frames contain references to all objects used in the method (of course there are other basic types of data). After the method is executed, the stack frames will pop up from the VM stack, in this way, the reference of the temporary object does not exist, or no gc room points to these temporary objects, these objects will be recycled in the next GC.
2. Objects referenced by class static attributes in the method area. A static attribute is a property of this type (class) and does not belong to any instance separately. Therefore, this attribute will naturally be used as gc roots. As long as this class exists, the object to which the reference points will always exist. Class will also be recycled.
3. Objects referenced by Native Stack
The following describes how to deal with soft reference and weakReference object garbage collection.
String str = new String("hello");//ASoftReference<String> sr = new SoftReference<String>(new String("java"));//BWeakReference<String> wr = new WeakReference<String>(new String("world"));//C
The recycling situations of the above objects are as follows. B will judge the String object as a recyclable object when the memory is insufficient, and C will be determined as a recyclable object under any circumstances. That is to say, soft references will be recycled when memory overflow (OOM) occurs, and weak references will be recycled in the next round in any case.
Generally, jvm recycles these objects.
1. explicitly assign a reference to null or point the reference that has already pointed to an object to a new object.
2. Local Reference refers to the object.
3. weakReference ).
Iii. Garbage Collection Algorithms
After determining which garbage can be recycled, the garbage collector starts to recycle the garbage. However, there is a problem: how to efficiently recycle the garbage. Java virtual machine specification does not clearly define how to implement the Garbage Collector. Therefore, virtual machines of various manufacturers can implement the Garbage Collector in different ways. Taking the most common HotShot as an example, so here we will only discuss the core ideas of several common 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 diagram comes from the network, which clearly shows the pre-processing and post-processing Memory Distribution of the algorithm.
It is easy to see that this operation has some disadvantages. After the marked object is clear, the memory block will become scattered. If an object occupies a large amount of memory, at this time, you must perform garbage collection to free up space for this large object.
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 replication algorithm will leave out the general memory in advance and move the remaining half of the memory when garbage collection is made. This way, memory movement consumes too much, although the memory is not fragmented, however, the cost is too high.
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 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, instead of recycling all objects, the new generation features that a large number of objects need to be recycled during each garbage collection, so we can adopt the most suitable collection algorithm based on the characteristics of different generations. You can call the System. gc () method to view the collection status.
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 new generation space is not divided by a ratio of. Generally, the new generation space is divided into a larger Eden space and two smaller than vor spaces, each time you use the Eden space and one of the other vor spaces, When you recycle the space, copy the surviving objects in the Eden and other vor to the other vor space, then, clear the Eden and the used volume vor space.
In the old age, only a small number of objects are recycled each time. Generally, the Mark-Compact algorithm is used.
Note that there is also a permanent Generation (Permanet Generation) outside the heap, which is used to store class classes, constants, and method descriptions. The recovery of permanent generation mainly involves two parts: discard constants and useless classes.
Iii. Typical Garbage Collector
The following are some simple things that I can understand and share with you.
1. Serial/Serial Old
The Serial/Serial Old collector is the most basic and oldest collector. It is a single-thread collector and must suspend all user threads when collecting garbage. The Serial collector is designed for the new generation of collectors and adopts the Copying algorithm. The Serial Old collector is designed for the collectors of the Old generation and uses the Mark-Compact algorithm. Its advantage is its simplicity and efficiency, but its disadvantage is that it will bring a pause to users.
2. ParNew
The ParNew collector is a multi-threaded version of the Serial collector. It uses multiple threads for garbage collection.
3. Parallel Scavenge
The Parallel Scavenge collector is a new generation of multi-thread collectors (Parallel collectors). It does not need to suspend other user threads during collection. It uses the Copying algorithm, the collector differs from the first two collectors to achieve a controllable throughput.
4. Parallel Old
Parallel Old is the Old version of the Parallel Scavenge collector (Parallel collector), using multithreading and the Mark-Compact algorithm.
5. CMS
The CMS (Current Mark Sweep) collector is a collector designed to obtain the minimum recovery pause time. It is a concurrent collector that uses the Mark-Sweep algorithm.
6. G1
The G1 collector is the most cutting-edge achievement in the development of collector technology. It is a collector for server applications and can fully utilize multi-CPU and multi-core environments. Therefore, it is a parallel and concurrent collector, and it can establish a predictable pause time model.
Iv. Summary and supplement
In general, the object memory is allocated on the stack. objects are mainly allocated in the new generation of Eden Space and From Space. In a few cases, they are directly allocated in the old age. If the Space of the new generation of Eden Space and From Space is insufficient, a GC is initiated. If GC is performed, eden Space and From Space can hold this object in Eden Space and From Space. During GC, the surviving objects in Eden Space and From Space are moved To Space, and Eden Space and From Space are cleaned up. If the To Space cannot store an object during the cleaning process, the object will be moved To the old age. After GC, the Eden space and To Space are used. The next GC will copy the surviving object To the From Space, so that the loops are repeated. If an object evades GC once in the same vor area, the object age is increased by 1. By default, if the object age reaches 15 years old, it will be moved to the old age.
In general, large objects will be directly allocated to the old age. The so-called large objects refer to objects that require a large number of consecutive buckets. The most common large object is a large array, for example:
Byte [] data = new byte [4*1024*1024]
In general, the storage space is directly allocated in the old age.
Of course, the allocation rules are not fixed, which depends on the current Garbage Collector combination and JVM-related parameters.