In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article will explain in detail how to analyze the JVM garbage collection principle. The content of the article is of high quality. Therefore, Xiaobian shares it with you as a reference. I hope that after reading this article, you will have a certain understanding of relevant knowledge.
overview
Java runtime area, program counter, virtual machine stack, local method stack three areas with thread and birth, with thread and death, these areas of memory allocation and collection are deterministic, do not need to consider too much collection problem. Java heap and method area is not the same, multiple implementation classes of an interface need different memory, multiple branches of a method may not need a glance of memory, we only in the runtime, can know the object will be created, this part of the memory allocation and collection, is the garbage collector is concerned about. The garbage collector has three questions to answer: what memory needs to be collected, when, and how.
That garbage needs recycling.
The basic idea of garbage collection is to examine the reachability of an object, that is, whether the object can be accessed from the root node. If it can, it means that the object is being used. On the contrary, if the object cannot be accessed from the root node, it means that the object is no longer used. Generally speaking, this object needs to be collected. This algorithm is called root search algorithm.
reachability analysis
But in practice, an unreachable object may "resurrect" itself under certain conditions, so its recycling is unreasonable. A definition of object reachability state is given, and the state under which objects can be safely reclaimed is specified. Reachability objects contain the following three states.
Reachable: Starting from the root node, according to the reference node, you can search for this object
Revivable: All references to the object are released, but the object may resurrect itself in the finalize() method.
Unreachable: The object's finalize() method is called and does not resurrect, then it enters the unreachable state. Unreachable objects cannot be "resurrected" because the finalize() method can only be called once.
/** * *
Description: 1. When an object is GC, it can be saved by finalize 2.finalize is called only once
* @date August 25, 2019 * @version 1.0 */public class FinalizeTest { private static FinalizeTest currentObj; @Override protected void finalize() throws Throwable { super.finalize(); System.out.println ("finalize invoke"); //re-reference currentObj = this; } public void alive() { System.out.println("live");} public static void main (String[] args) throws InterruptedException { currentObj = new FinalizeTest(); currentObj = null; System.gc(); //finalize priority, wait for Thread.sleep(500); if (currentObj == null) { System.out.println("dead"); }else { currentObj.alive(); } currentObj = null; System.gc(); //finalize priority, wait Thread.sleep(500); if (currentObj == null) { System.out.println("dead"); }else { currentObj.alive(); } }}
The above code has the same broken code fragment, but the results are not the same. Once the object "rescue and resurrection" succeeds, the other fails, so it can be recovered normally.
GC Roots include the following:
Objects referenced in the virtual machine stack (native table count in stack frame) Objects referenced by static attributes in the method section Objects referenced by constants in the native method stack Objects referenced by JNI (i.e., generic Native methods)
Four types of references
After JDK 1.2, references were expanded and divided into four types: strong references, soft references, weak references and virtual references. These four strengths were weakened once. By extending references, objects can be described in terms of memory usage: when memory is sufficient, they are retained in memory; if memory space is still tight after garbage collection, they can be discarded. The caching capabilities of many systems fit into this application scenario.
strong reference
The most common thing in Java is a strong reference, assigning an object to a reference variable, and this reference variable is a strong reference. When an object is referenced by a strongly referenced variable, it is reachable and cannot be collected by garbage collection, even if the object is never used by the JVM. Therefore, strong references are one of the main causes of Java memory leaks.
soft references
Soft references need to be implemented with the SoftReference class. For objects with only soft references, they are not recycled when the system memory is sufficient, and they are recycled when the system memory space is insufficient. Soft references are commonly used in memory-sensitive programs.
weak references
Weak references need to be implemented with the WeakReference class, which has a shorter lifetime than soft references. For objects with only weak references, as long as garbage collection is running, regardless of whether the JVM has enough memory space, the memory occupied by the object will always be collected.
Phantom reference
Virtual references require the PhantomReference class to implement them. They cannot be used alone, but must be used in conjunction with reference queues. The main purpose of virtual references is to track the state of objects that are garbage collected.
When to recycle
According to the implementation of serial GC of HotSpot VM, trigger conditions are mainly divided into the following types:
young GC: Triggers when the eden area in young gen is full. Note that some surviving objects in young GC will be promoted to old gen, so the old gen occupancy will usually increase after young GC. full GC: When preparing to trigger a young GC, if statistics show that the average promotion size of the previous young GC is larger than the remaining space of the current old gen, young GC will not be triggered but full GC will be triggered instead.(Because in HotSpot VM's GC, except for CMS's concurrent collection, other GC that can collect old gen will collect the entire GC heap at the same time, including young gen, so there is no need to trigger a separate young GC in advance); Or, if there is perm gen, if you want to allocate space in perm gen but there is not enough space, you also need to trigger a full GC; or System.gc(), heap dump with GC, the default is also triggered full GC.
The trigger conditions for other non-concurrent GC in HotSpot VM are more complex, but the general principle is the same as described above. The trigger conditions for concurrent GC are different. Take CMS GC as an example. It mainly checks the usage of old gen regularly. When the usage exceeds the trigger ratio, CMS GC will be started once to collect old gen concurrently.
how to recycle
How to recycle mainly involves the garbage collection algorithm. The following describes the idea of several garbage collection algorithms.
Mark-Sweep
Tag cleaning algorithm is the ideological basis of modern garbage collection algorithm. It is divided into two phases: marking phase and cleaning phase. In the marking phase, all reachable queue objects starting from the root node are marked first by the root node, so that unmarked objects are unreferenced garbage objects. Then in the cleanup phase, all untagged objects are cleared.
The shortcomings of the marker-clearing algorithm include efficiency problems and a large number of discontinuous memory fragments after marker-clearing. Too much fragmentation may result in large objects being allocated without contiguous memory and having to trigger another garbage collection early.
Coping algorithm
The core idea of the copy algorithm is to divide the original memory space into two blocks, only use one of them at a time, copy the surviving objects in the memory being used to the unused memory block during garbage collection, and then clear all objects in the memory block being used, exchange the roles of the two memories, and complete garbage collection.
If there are many objects to be collected in the system, the replication algorithm needs to copy relatively few surviving objects, and the efficiency of the replication algorithm will be very high at the time of real garbage collection. Moreover, the objects are copied to the new memory space in the garbage collection process, and then the original memory used is cleared, so it can be ensured that the memory space after collection is free of fragments. On the other hand, the cost of the replication algorithm is that it requires more memory space.
Replication algorithm is more suitable for the Cenozoic generation. Because new generation garbage objects usually have more surviving objects, the replication algorithm is more efficient.
Mark Compact
In the old days, most of the objects were living objects. If we still use the replication algorithm, the cost of replication will increase due to the large number of surviving objects. Therefore, based on the old garbage collection characteristics, other algorithms need to be used. Mark sorting algorithm is an old recycling algorithm. It makes some optimizations on the basis of labeling algorithm. Like the marker-purge algorithm, it starts at more nodes, but instead of purging unmarked objects, it compresses surviving objects to one side of memory and then purges all space outside the boundary. This method avoids fragmentation and does not require too much memory space, so it is cost-effective.
The final effect of the mark defragmentation method is equivalent to the defragmentation of memory after the completion of the mark cleanup algorithm, so it can also be called Mark Sweep Comact.
Generational Collection
Generational algorithm is to divide the memory into several blocks according to different object life cycle. Java heap is generally divided into the new generation and the old age, so that the most appropriate collection algorithm can be adopted according to the characteristics of each age. Cenozoic is characterized by the rapid birth and death of objects, about 90% of the new objects will be recycled, so Cenozoic suitable for replication algorithms. When an object survives several evictions, the object is placed in the old memory space. In old age objects can be thought of as memory resident for a period of time, even throughout the life cycle of the program, and can be used for old age with tag cleaning and tag defragmentation algorithms.
For both the Cenozoic and the older generations, the recovery frequency is usually high in the Cenozoic, but each recovery takes a short time, while the recovery frequency in the older generation is lower, but it takes more time.
Region algorithm
In general, under the same conditions, the larger the heap space, the longer the events required for a GC, and thus the longer the pause. For better pause time, divide a large memory area into small areas of the same size, and reclaim several small areas at a time, rather than the entire heap space, based on the target pause time, thereby reducing the pause caused by a GC. Partitioning algorithm divides the whole heap space into different continuous cells. Each cell is used independently and recovered independently.
How to parse the JVM garbage collection principle is shared here. I hope the above content can be of some help to everyone and learn more knowledge. If you think the article is good, you can share it so that more people can see it.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.