Introduction to Garbage collection
?? The Java Virtual machine memory partition refers to the Java Memory Runtime area of the various parts, where the program counter, virtual machine stack, the local method stack three regions with the thread, the stack frame in the stack with the method entry and exit methodically execute the stack and into the stack operation. How much memory is allocated in each stack frame is basically defined in the class structure to be already cicada. Therefore, memory allocation and recycling in these areas are deterministic, and in these areas there is a need to think too much about recycling, because when the method ends or the thread ends, the memory is naturally recycled. While the Java heap and the method area are different, multiple implementation classes in an interface may require different memory, and multiple branches in one method may require different memory, and we can only know which objects are created when the program is running, and this portion of memory allocation and recycling is dynamic. The garbage collector is concerned with this part of the memory.
Method of judging Garbage object
?? In the heap is the storage of almost all object instances in Java, before garbage collection, the first to determine which objects should be recycled.
Reference counting algorithm
The reference counting method is one of the familiar methods.
The algorithm process is as follows:
Add a reference counter to the object, the counter value is incremented by 1 whenever there is a reference to it, and when the reference fails, the counter value is reduced by one, and the object with counter 0 at any time is impossible to be used again.
This method is characterized by simple implementation and high efficiency of judgment, which is a good choice in most cases. However, many mainstream Java virtual machines do not choose to use the reference counting class to manage memory, mainly because it is difficult to solve the problem of circular referencing between objects.
publicclass MyObject { publicrefnull; publicstaticvoidmain(String[] args) { new MyObject(); new MyObject(); myObject1.ref = myObject2; myObject2.ref = myObject1; null; null; }}
Circular references cause both MyObject1 and myObject2 to have two referenced times of 2, even if two objects are set to NULL, the number of references is still 1, resulting in two objects not being recycled.
Accessibility analysis algorithm
In the mainstream implementation of mainstream commercial programming languages (such as java,c#), the accessibility analysis is used to determine whether an object survives.
The algorithm process is as follows:
?? The basic idea of this algorithm is to use a series of objects called "GC Roots" as the starting point, starting from these nodes to search down, searching through the path called the reference chain. When an object is connected to a GC roots without any reference chain, it proves that the object is not available. As shown, object Object5,object6,object7, although associated with each other, are not accessible to GC roots, so they will be judged as recyclable objects.
In Java, the objects that can be used as GC roots include the following:
1. 虚拟机栈(栈帧中的本地变量表)中引用的对象。2. 方法区中类静态属性引用的对象。3. 方法区中常量引用的对象。4. 本地方法栈中JNI(即一般说的Native方法)引用的对象。
?? Even those unreachable in the Accessibility analysis algorithm are not "immortal", when they are temporarily in the "probation stage", to truly declare an object to die, at least two times to go through the marking process: If an object is found to have no reference chain connected to GC roots after accessibility analysis, Then it will be marked for the first time and filtered to see if it is necessary for this object to execute the Finalize () method. When the object does not overwrite the Finalize () method, or the Finalize () method has been called by the virtual machine, the virtual machine treats both cases as "no need to execute".
If this object is judged to be necessary to execute the Finalize () method, then the object will be placed in a queue called F-queue and executed later by a low-priority finalizer thread that is automatically created by a virtual machine. The so-called "execution" here means that the virtual opportunity triggers this method, but does not guarantee that it will wait for the end of its run, because if an object executes slowly in the Finalize () method, or if a dead loop (extreme) occurs, Will most likely cause other objects in the F-queue queue to be permanently waiting, even causing the entire memory-recycling system to crash. The Finalize () method is the last chance for an object to escape the fate of death, and later the GC will make a second small-scale mark on the object in F-queue, if the object is to successfully save itself in Finalize ()-just re-associate with any object on the reference chain. For example, assigning yourself (the This keyword) to a class variable or to a member variable of an object, it will be removed from the collection that is "about to be recycled" at the second mark, and if the object has not escaped at this time, it is basically recycled.
Garbage collection algorithm
?? In fact, the implementation of garbage collection algorithm involves a lot of program details, and the various platforms of virtual machine operating memory methods are different, so we only discuss the basic idea of several algorithms. The common garbage collection algorithm mainly involves these kinds of, marking-clearing algorithm, copying algorithm, labeling sorting algorithm, generation collection algorithm, etc., the following one by one as an introduction.
Tag--Clear algorithm
?? This is the most basic collection algorithm (Mark-sweep). Divided into markers-clear two phases.
Marking stage: First mark out all the objects that need to be recycled, and after the mark is complete, all tagged objects are collected uniformly, and the tagging process is actually the tagging process in the accessibility analysis algorithm described above. It is the most basic algorithm, and the subsequent collection algorithm is based on this idea and the improvement of its shortcomings are obtained.
The main deficiencies are two:
1. Efficiency issues, marking and removal of two processes are not efficient.
2. Space problems, marked by the removal of a large number of discontinuous fragments, may result in subsequent programs need to allocate large objects, cannot find enough contiguous memory and have to trigger another garbage collection action. The execution process is as follows:
Replication Algorithms
?? On the basis of the above-mentioned mark-sweep algorithm, in order to solve the efficiency problem, the replication algorithm appears, which divides the available memory by capacity into two blocks of equal size, using only one piece at a time. When this piece of memory is exhausted, copy the surviving object to the other piece, and then clean up the used memory space once. This makes every time the entire half of the memory collection, memory allocation will not consider the complexity of memory fragmentation, as long as the move to the top pointer, in order to allocate memory, easy to implement, efficient operation.
The disadvantage is that the memory is reduced to half the original, the cost is higher, when the object survival rate is higher, the more replication operation, the efficiency will be lower.
Application scenario: used in today's mainstream commercial virtual machine generation collection algorithm , the difference is that the actual generation of collection algorithm, not simply divided into two halves of the memory, but the memory is divided into a large Eden space and two small survivor space, Use only Eden and one piece of survivor at a time. For the specific contents of the heap area and Cenozoic, refer to the Java Virtual Machine (ii)-Heap memory partition.
Tagging--Finishing algorithms
?? The replication collection algorithm will perform more replication operations when the object has a higher survival rate, and the efficiency is reduced. More crucially, if you do not want to waste 50% of space, you need to have additional space for the allocation of security to deal with all the objects in the memory used in 100% survival extreme situation, so the old age is generally not directly select this algorithm.
The mark-and-sweep algorithm (mark-compact) marks the same procedure as the "mark-purge" algorithm, but the next step is not to clean up the recyclable objects directly, but rather to have all the objects in stock move toward one end, and then directly clean out the memory outside the end boundary.
Generational collection Algorithms
?? The generational collection algorithm is the algorithm used by the garbage collection mechanism of the commercial virtual machine at present. the Generational collection algorithm is not a new algorithm model, it is a comprehensive application of different collection algorithms according to the different characteristics of the object survival period. Specifically, the garbage collection scheme used in the heap area. Heap is divided into the new generation and the old age, the new generation of features is that each garbage collection will find a large number of objects to die, only a small number of survival, then the use of replication algorithm, only a small number of surviving objects can be copied cost to complete the collection, which is called minor GC. The old age is characterized by the high survival rate of the object, and the lack of additional space to guarantee its distribution, then it must use the "mark-clear" or "mark-tidy" algorithm.
Common garbage collector implementations
?? The garbage collector is a specific implementation of memory reclamation. Of course, the Java Virtual Machine specification on how to implement the garbage collector does not have any provisions, in fact, so far not the best collectors appear, there is no universal collector, so we choose only the most appropriate for the application of the collector.
Serial Collector
?? It is the most basic, longest-growing collector, once the only choice for the new generation of virtual machines. Feature is that it is a "single-threaded" collector, so-called "single-threaded" means that it does not only use a CPU or a collection thread to complete the garbage collection work, more importantly, when it is garbage collected, all other worker threads must be paused until it is collected to the end. This is obviously unacceptable, but modern virtual machines are constantly optimized to reduce the time to pause, and the pause time can be fully controlled at a maximum of dozens of milliseconds, up to 100 milliseconds, so long as it is not frequent, this pause is perfectly acceptable. For a virtual machine running in client mode, such as a user's desktop scenario, the memory allocated to the virtual machine management is generally not too large to collect a few 10 trillion or even one hundred or two hundred trillion of new generation, the serial collector is fully sufficient. The main advantage is that, without the overhead of thread interaction, concentrating on garbage collection naturally provides the highest single-thread collection efficiency .
Parnew Collector
?? Parnew is a multithreaded version of serial, the core of which is to use multiple threads for garbage collection. However, in a single CPU environment is absolutely no better than the serial collector, even due to the cost of thread interaction, the collector in Hyper-Threading technology implementation of the two CPU environment can not be guaranteed to exceed the serial collector. But when the number of available CPUs increases, the system resources can be used more efficiently.
The Parnew collector, in addition to multi-threaded collection, does not have much innovation compared to the serial collector, but it is the preferred Cenozoic collector for many virtual machines running in server mode, one reason being that, in addition to the serial collector, Currently only it can work with the CMS collector.
Parallel Scavenge Collector
?? Parallel Scavenge Collector It is a new generation collector . In particular, the focus of other collectors is to minimize the downtime of user threads when garbage collection is minimized, and the goal of the Parallel scavenge collector is to achieve a controlled throughput. throughput = Run user code time/(run user code time + garbage collection time), assuming the virtual machine is running for 100 minutes and garbage collection takes 1 minutes, then throughput is 99%. The Parallel scavenge collector provides a number of detailed parameters that can be precisely set to precisely control the maximum garbage collection pause time and throughput size, especially when the adaptive parameters are open and do not need to manually specify the new generation size and other details, The virtual opportunity collects performance monitoring information based on the current system's operation and dynamically adjusts these parameters to provide the most appropriate pause time or maximum throughput, which is known as the GC Adaptive throttling strategy.
Adaptive strategy is also an important difference between the parallel scavenge collector and the Parnew collector.
Serial Old Collector
?? The Serial old collector is an older version of the Serial collector, which is also single-threaded, using the "mark-and-Organize algorithm". The main purpose of this collector is to use the virtual machine in client mode.
Parallel Old Collector
?? The Parallel old collector is an older version of the Parallel scavenge, using multithreading and the "mark-and-organize" algorithm. This collector is not available until JDK 1.6 has started.
The parallel scavenge plus parallel old collector is a priority when it comes to throughput and CPU resource sensitivity.
CMS collector
?? The CMS (Concurrent Mark Sweep) collector is implemented based on the "tag-purge" algorithm, which uses a multithreaded algorithm to scan the heap (tag) and reclaim (clear) the discovered unused objects. The entire process is divided into 6 steps, including:
初始标记(CMS initial mark)并发标记(CMS concurrent mark)并发预清理(CMS-concurrent-preclean)重新标记(CMS remark)并发清除(CMS concurrent sweep)并发重置(CMS-concurrent-reset)
?? Where the initial tag, re-tagging these two steps still need "Stop the World". The initial tag simply marks the object that the GC Roots can directly relate to, is fast, the concurrent tagging phase is the process of GC Roots tracing, and the re-tagging phase is to fix the concurrency tag period. The mark record of the part of the object that caused the tag to change as the user program continues to work, the period of time will generally be slightly longer than the initial marking phase, but much shorter than the time of the concurrent tag. All other actions are concurrent.
?? Note that the CMS collector is unable to handle floating garbage (floating garbage), and a "Concurrent Mode Failure" failure may occur resulting in another full GC. Because the CMS concurrent cleanup phase of the user thread is still running, along with the program's operation naturally there will be new garbage constantly generated, this part of the garbage in the marking process, the CMS will not be able to dispose of them in this collection, we have to leave the next GC to clean it off. This part of the rubbish is called "floating rubbish". Also because the user thread in the garbage collection phase also needs to run, that is, the need to reserve enough memory space for the user thread to use, so the CMS collector cannot wait until the old age is almost completely filled up like the other collectors and then collect it, and it needs to reserve a portion of the space for the program to run when it is collected concurrently. In the default settings, the CMS collector will be activated after using 68% of the space in the old age, which is a conservative setting, if the old-age growth in the application is not too fast, you can properly adjust the parameter-xx: The cmsinitiatingoccupancyfraction value to increase the trigger percentage to reduce the number of memory recoveries for better performance. If the memory reserved during the CMS operation does not meet the needs of the program, a "Concurrent Mode Failure" failure occurs, when the virtual machine will start a fallback plan: temporarily enable the serial old collector to re-age garbage collection, so the pause time is very long. So the parameter-xx:cmsinitiatingoccupancyfraction set too high will easily lead to a lot of "Concurrent Mode Failure" failure, performance is reduced.
?? Another drawback is that theCMS is a collector based on the "tag-clear" algorithm, which means that the collection ends up with a lot of space fragmentation . When there is too much space debris, large objects will be assigned a lot of trouble, often the old age still has a lot of space remaining, but can not find enough contiguous space to allocate the current object, have to trigger a full GC in advance. To solve this problem, the CMS collector provides a-xx:+usecmscompactatfullcollection switch parameter for additional free defragmentation after "enjoy" the full GC service, and the process of memory grooming is not concurrent. The space debris problem is gone, but the pause time must not be longer. Virtual machine designers also provide another parameter,-xx:cmsfullgcsbeforecompaction, which is used to set the number of uncompressed full GC, followed by a compressed one at a time.
?? Another disadvantage of the algorithm with the parallel collector is that it uses more CPUs for throughput, in order to enable the application to provide a better experience by using multiple threads to perform scanning and collection. This is a situation where the application pauses for a long time and can be used to improve space for efficient operation. However, the use of this algorithm is not the default. You must specify XX: + USEPARNEWGC to use it. If you can provide more CPU resources to avoid application pauses, then you can use the CMS collector. Assuming that your heap size is less than 4 GB, you must allocate more than 4 GB of resources.
G1 Collector
?? The G1 garbage collector has better support for heaps larger than 4G after JDK7 update 4, and theG1 is a server-side garbage collector for multiprocessor high-capacity memory , with the goal of meeting the garbage collection pause time as much as possible while achieving high throughput. G1 is performed concurrently with the application thread when performing full-area operations in some Java heap space, such as global markup, thereby reducing the percentage of disruption to the Java heap space. (Translator Note: Can be simply understood to reduce the stop-the-world time ratio).
?? It has two notable improvements over the previous CMS collector: one is that the G1 collector is a collector based on the "mark-and-organize" algorithm, meaning it does not produce space debris, which is important for long-running applications. The second is that it can control the pauses very precisely, which allows the user to explicitly specify that in a time fragment of length m milliseconds, the time spent on garbage collection should not exceed n milliseconds, with some real-time Java (RTSJ) garbage collector characteristics.
?? The Java heap space is first divided into areas of equal size (region), each of which is a contiguous memory space in the virtual machine. G1 determines the surviving objects in the entire Java heap space by executing a concurrent global tag. When the tagging phase is complete, G1 knows which areas are essentially idle. These areas are reclaimed preferentially when the memory is reclaimed, which usually reclaims a significant amount of memory. That's why it's called Garbage-first. As the name implies, G1 focuses on the recycling and collation of certain areas where objects are most likely to be fully reclaimed. And G1 uses a pause-time prediction model that allows the pause time to be controlled within the user-specified pause time and to select the appropriate area to reclaim memory based on the user-specified pause time.
?? G1 determines the recoverable area is the filter recovery (evacuation) stage. At this stage, the objects are copied from one or more zones to a single region, while the memory is organized and freed. This phase is performed in parallel on multiple processors, thus reducing the pause time and increasing throughput. G1 continuously reduces fragmentation during each garbage collection process and is able to control the pause time within a certain range. These are already the previous garbage collectors cannot complete. For example: CMS collector does not do memory collation. The Parallelold collector simply collates the entire Java heap space, which results in a considerable pause time.
Java Virtual Machine (v)--garbage collection mechanism