Reference counting algorithm
Many textbooks determine whether an object survives the algorithm is this: Add a reference counter to the object, whenever there is a place to reference it, the counter value is added 1, when the reference fails, the counter value is reduced by 1, any time the counter is 0 of the object is impossible to be used again.
Objectively speaking, the reference counting algorithm (Reference counting) implementation is simple, the decision efficiency is very high, in most cases it is a good algorithm, there are some more famous application cases, such as Microsoft's COM (Component Object Model) technology, Flashplayer using ActionScript 3, the Python language, and squirrel, which are widely used in the game scripting world, use reference counting algorithms for memory management. However, the Java language does not use the reference counting algorithm to manage memory, the most important of which is that it is difficult to solve the problem of mutual circular references between objects.
Root Search algorithm
In the mainstream of commercial programming languages (Java and C #, even the old Lisp mentioned earlier), the root search algorithm (GC Roots tracing) is used to determine whether an object survives. 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, the path of the search is called the reference chain (Reference Chain), when an object to the GC Roots no reference chain is connected (in the case of graph theory, from GC roots to the object unreachable) , it proves that this object is not available. As shown in 3-1, objects 5, 6, and object 7 are associated with each other, but they are not accessible to GC roots, so they will be judged as recyclable objects.
In the Java language, the objects that can be used as GC roots include the following:
- The referenced object in the virtual machine stack (the local variable table in the stack frame).
- The object referenced by the class static property in the method area.
- The object referenced by a constant in the method area.
- The object referenced by the JNI (that is, the generally said native method) in the local method stack.
|
|
|
Figure 3-1 The root search algorithm determines whether an object can be recycled |
Talk about references again
After JDK 1.2, Java extends the concept of references into strong references (strong Reference), soft references (Soft Reference), weak references (Weak Reference), virtual references (Phantom Reference) Four species, these four kinds of reference strength gradually weakened.
A strong reference is a common reference in program code, such as "Object obj = new Object ()", as long as a strong reference exists, and the garbage collector never reclaims the referenced object.
Soft references are used to describe some objects that are also useful, but are not required. For objects associated with soft references, these objects are listed in the collection scope and recycled a second time before the system will have a memory overflow exception. If this collection still does not have enough memory, the memory overflow exception will be thrown. After JDK 1.2, the SoftReference class was provided to implement soft references.
A weak reference is also used to describe a non-required object, but its strength is weaker than a soft reference, and the object associated with the weak reference only survives until the next garbage collection occurs. When the garbage collector is working, the objects associated with a weak reference are reclaimed regardless of whether the current memory is sufficient. After JDK 1.2, the WeakReference class was provided to implement weak references.
A virtual reference , also known as a phantom reference or phantom Reference, is the weakest reference relationship. Whether an object has a virtual reference exists, does not affect its lifetime at all, and cannot obtain an object instance through a virtual reference. The only purpose of setting a virtual reference association for an object is to expect to receive a system notification when the object is reclaimed by the collector. After JDK 1.2, the Phantomreference class is provided to implement the virtual reference.
To survive or to die?
Objects that are unreachable in the root search algorithm are not "dead", and they are temporarily in the "probation" stage to actually declare an object to die, at least two times to go through the tagging process : If the object finds no reference chain connected to the GC roots after the root search, 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 named F-queue , and then executed by a low priority finalizer thread that is automatically created by the virtual machine at a later time. . The so-called "execution" here refers to the virtual opportunity to trigger this method, but does not promise to wait for it to run over. The reason for this is that if an object executes slowly in the Finalize () method, or if a dead loop (more extreme) occurs, it is likely to cause other objects in the F-queue queue to be permanently waiting, or even to crash the entire memory-recycling system. 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 objects in the F-queue , if the object is to successfully save itself in Finalize ()- Simply re-associate with any object on the reference chain, such as assigning yourself (the This keyword) to a class variable or a member variable of an object, it will be removed from the collection "About to be recycled" at the second mark, and if the object has not escaped at this time, it is really not far from dead. From code listing 3-2 we can see that the Finalize () of an object is executed, but it can still survive.
Recycling Method Area
Many people think that the method area (or the permanent generation in the Hotspot virtual machine) is not garbage collected, and the Java Virtual Machine specification does say that virtual machines can not be required to implement garbage collection in the method area, and that the "price/performance" of garbage collection in the method area is generally low: in the heap, especially in the Cenozoic, Regular applications do a garbage collection generally can reclaim 70%~95% space, and the garbage collection efficiency of the permanent generation is much lower than this.
The garbage collection of the permanent generation mainly recycles two parts: obsolete constants and useless classes.
Reclaiming obsolete constants is very similar to reclaiming objects in the Java heap. For example, if a string "ABC" has entered a constant pool in the case of a constant pool literal, the current system does not have any string object called "abc", in other words, there is no string object referencing the "ABC" constant in the constant pool. There is no other place to quote this literal, and if a memory recycle occurs at this time, and if necessary, the "ABC" Constant will be "please" out of the constant pool. The symbolic references to other classes (interfaces), methods, and fields in a constant pool are similar.
Classes need to meet the following 3 conditions to be considered "useless classes":
- All instances of the class have been reclaimed, that is, no instances of the class exist in the Java heap.
- The ClassLoader that loaded the class have been recycled.
- The corresponding Java.lang.Class object of this class is not referenced anywhere and cannot be used to access the class's methods at any place.
New Generation (young), older generation (old)
The heap in Java is the largest memory space managed by the JVM and is primarily used to store instance objects of various classes.
In Java, the heap is divided into two different areas: the New Generation (young), the old generation (older).
- Young: It is mainly used to store new objects.
- Old: Primarily stores memory objects that have a long life cycle in the application.
PS: In fact, there is a concept of a permanent generation, is used to store information in the method area, the concept is outdated, the method area of information will change, and hotspot is also the abolition of permanent generation.
The New Generation (young) is divided into three regions: Eden, from Survivor, to Survivor.
The purpose of this partitioning is to enable the JVM to better manage the objects in the heap memory, including the allocation of memory and recycling.
The memory model of the heap is roughly:
You can see: heap size = new Generation + old age. The size of the heap can be specified by parameter –xms,-xmx.
Garbage collection algorithm tag-purge algorithm
The most basic collection algorithm is the "mark-clear" (mark-sweep) algorithm, like its name, the algorithm is divided into "mark" and "clear" two stages: first mark out all the objects that need to be recycled, after the mark is completed, the unified collection of all tagged objects, Its tagging process has been basically introduced in the previous section about object tag determination. The reason is that it is the most basic collection algorithm, because the subsequent collection algorithms are based on this idea and improve their shortcomings. Its main shortcomings are two: one is the efficiency problem , the labeling and removal process is not efficient, and the other is a space problem , the mark after the purge will produce a large number of discontinuous memory fragmentation, too much space debris may cause, When the program needs to allocate large objects in the future, it cannot find enough contiguous memory and has to trigger another garbage collection action in advance.
Replication Algorithms
To solve the efficiency problem, a collection algorithm called "Replication" (Copying) appears, dividing 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 each one of the pieces of memory recycling, memory allocation will not consider the complexity of memory fragmentation, as long as the mobile heap top pointer, in order to allocate memory, simple implementation, efficient operation. But the cost of this algorithm is to reduce the memory to half of the original, it is a little too high.
today's commercial virtual machines are using this collection algorithm to reclaim the new generation, IBM's special research shows that the new generation of object 98% is facing to die, so do not need to follow the 1:1 ratio to divide the memory space, Instead, it divides the memory into a larger Eden space and two smaller survivor spaces, each using Eden and one of the survivor. When recycled, the objects that are still alive in Eden and survivor are copied one at a time into another survivor space, finally clearing the space of Eden and the survivor that was just used. The default Eden and survivor size ratio of the hotspot virtual machine is 8:1, which is 90% (80%+10%) of the total Cenozoic capacity for each generation, and only 10% of the memory is "wasted". Of course, 98% of the objects can be recycled only in the general scenario of the data, we have no way to ensure that only a few more than 10% per collection of objects to survive, when the survivor space is not enough, you need to rely on other memory (this refers to the old age) for the allocation of security (Handle Promotion).
Memory allocation guarantee is like we go to the bank to borrow money, if we have good reputation, in 98% of the situation can be repaid on time, so the bank may be the default we will be able to repay the loan on time, only need a guarantor can guarantee if I can not pay, the bank will be deducted from his account, the banks think there is no risk. The memory allocation guarantee is also the same, if another piece of survivor space does not have enough space to hold the last generation of surviving objects collected, these objects will be directly through the allocation of security mechanisms into the old age.
Tagging-sorting algorithms
According to the characteristics of the old age, someone proposed another "mark-and-sweep" (mark-compact) algorithm, the marking process is still the same as the "tag-purge" algorithm, but the next step is not directly to the recyclable objects to clean up, but to let all the surviving objects moved to one end, Then directly clean out the memory outside the end boundary, as shown in 3-4 of the "mark-and-organize" algorithm.
Generational collection Algorithms
The current garbage collection of commercial virtual machines uses the "generational collection" (generational Collection) algorithm, which does not have any new ideas, but divides the memory into several blocks based on the different life cycles of the objects. The Java heap is generally divided into the new generation and the old age , so that according to the characteristics of each era to adopt the most appropriate collection algorithm. in the Cenozoic , every garbage collection is found to have a large number of objects died, only a small number of survival, then choose the replication algorithm , only need to pay a small number of surviving objects of the replication cost can be completed collection. in the old age , because of the high survival rate of the object and the lack of additional space to guarantee it, it must be recycled using the "mark-clean" or "mark-sweep" algorithm .
Garbage collector
If the collection algorithm is the method of memory recycling, the garbage collector is the specific implementation of memory recycling.
There is no universal collector, so we choose only the most appropriate collector for the specific application.
The following is a list of the Sun hotspot collectors:
New generation: Serial collector
The serial collector is the most basic and oldest collector, the collector of the copy algorithm, once (before the JDK 1.3.1) is the only choice for the virtual machine generation collection. As you can see by name, this collector is a single-threaded collector, but its "single-threaded" meaning is not just about using a CPU or a collection thread to do garbage collection, but more importantly, when it's garbage collected, it must pause its All of his working threads (Sun will call this thing "Stop the World") until it collects the end.
Parnew Collector
The Parnew collector is actually a multithreaded version of the serial collector. The collector for the copy algorithm,
Parallel Scavenge Collector
The Parallel scavenge collector is also a new generation collector, it is also a collector using the replication algorithm, and is also a parallel multi-threaded collector. The Parallel scavenge collector is characterized by its focus on other collectors, where the focus of collectors such as CMS shortens the user thread's pause time as much as possible, while Parallel The target of the scavenge collector is to achieve a controllable throughput (throughput). The so-called throughput is the ratio of the CPU's time spent running user code to the total CPU time consumed.
Older: Serial old collector
Serial old is an older version of the Serial collector, which is also a single-threaded collector, using the "mark-and-organize" algorithm.
Parallel Old Collector
Parallel old is an older version of the Parallel scavenge collector, using multithreading and the "mark-and-organize" algorithm.
CMS collector
The CMS (Concurrent Mark Sweep) collector is a collector that targets the shortest recovery pause time. At present, a large part of the Java applications are concentrated in the Internet or B/s system services, such applications pay particular attention to the response of the service, the hope that the system will be the shortest time to pause, in order to bring a better user experience. CMS collectors are very much in line with the needs of such applications.
From the name (including "Mark Sweep") you can see that the CMS collector is implemented based on the "tag-purge" algorithm, its operation is more complex than the previous collectors, the entire process is divided into 4 steps, including:
Initial tag (CMS initial mark)
Concurrency token (CMS concurrent mark)
Re-tagging (CMS remark)
Concurrent Purge (CMS concurrent sweep)
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.
But the CMS is far from perfect, and it has the following three notable drawbacks:
- The CMS collector is very sensitive to CPU resources. In fact, concurrent design-oriented programs are more sensitive to CPU resources.
- 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.
- CMS is a collector based on the "tag-clear" algorithm, and if the reader is impressed with the previous algorithm introduction, it might be thought that this means that the collection ends up with a lot of space debris.
G1 Collector
The G1 (garbage first) collector is the forefront of current collector technology development and provides a G1 collector of early access versions for trial use in JDK 1.6_update14. When JDK 1.7 is released in the future, it is likely that the G1 collector will be released with a mature commercial version.
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 in a time fragment of length m milliseconds, the time spent on garbage collection should not exceed n milliseconds, which is almost a feature of the real-time Java (RTSJ) garbage collector.
Common parameters related to garbage collection
memory allocation and recovery policy
The memory allocation of objects, in the general direction, is allocated on the heap (but can also be JIT-compiled and then split into scalar types and indirectly allocated on the stack), the object is mainly allocated to the new generation of Eden area, if the local thread allocation buffer is started, it will be assigned by thread priority on Tlab. In a few cases it may also be assigned directly in the old age, the allocation rules are not completely fixed, the details depend on which garbage collector combination is currently in use, and the settings of the memory-related parameters in the virtual machine.
Several of the most common memory allocation rules:
- Objects take precedence over Eden allocations: In most cases, objects are allocated in the New Generation Eden area. When the Eden area does not have enough space to allocate, the virtual machine will initiate a minor GC.
- Large objects go straight into the old age: the so-called Big object is the Java object that needs a lot of contiguous memory space, the most typical large object is that long string and array. This is done to avoid a large amount of memory duplication between the Eden area and the two survivor zones. a large object is a bad message for the memory allocation of a virtual machine (for a Java virtual machine to complain that more bad news than encountering a large object is to encounter a group of "short-lived big objects", to write programs should be avoided), Often large objects tend to cause memory to have plenty of space to trigger garbage collection ahead of time to get enough contiguous space to "place" them. (PS: So, if we are going to read a string from a stream, or use a Reade 1.1-point reading, though it will eventually go into memory, we can avoid reading the byte array from the stream).
- Long-lived objects will enter the old age, and the virtual machine defines an object age counter for each object. If the object is still alive after Eden was born and after the first minor GC, and can be accommodated by survivor, it is moved to survivor space and the object age is set to 1. Object in the Survivor area each time minor GC, age increases by 1 years, when its age to a certain extent (by default, 15 years old), will be promoted to the old age.
What's the difference between the Minor GC and the full GC?
New Generation GC (Minor GC): Refers to the garbage collection action occurring in the Cenozoic, because most Java objects have the characteristics of being born and going out, so the Minor GC is very frequent, and the general recovery speed is relatively fast.
Old age GC (Major gc/full GC): Refers to the GC, which occurred in the old age, Major GC, often accompanied at least once minor GC (but not absolute, in the Parallelscavenge Collector's collection strategy is directly Major GC's policy selection process). The speed of the MAJORGC is generally 10 times times slower than the minor GC.
Space Allocation guarantee
When the minor GC occurs, the average size of each promotion to the old age is greater than the remaining space size of the old age before the virtual opportunity is detected, and if it is greater, the full GC is changed directly. If it is less than, see if the Handlepromotionfailure setting allows the warranty to fail; if allowed, only minor GC will be performed, and if not allowed, a full GC should be performed instead.
Deep understanding of Java Virtual Machine garbage collector and memory allocation policy