Java Virtual Machine detailed----GC Algorithms and types

Source: Internet
Author: User

The main content of this article:

    • The concept of GC
    • GC algorithm

Reference counting method (cannot solve the problem of circular reference, not accepted by Java)

Root Search algorithm

Garbage collection algorithms in modern virtual machines:

Mark-Clear

Replication Algorithm (Cenozoic)

Tag-compression (old age)

Collection of generations

    • Accessibility
    • Stop-the-world

First, the concept of GC:

    • Gc:garbage Collection Garbage Collection
    • 1960 Lisp uses a GC
    • In Java,the GC object is the Java heap and the method area (that is, the permanent zone)

We'll then explain the above three sentences in one by one:

(1) Gc:garbage Collection garbage collection. Here the so-called garbage refers to the system in the process of the production of some useless objects, these objects occupy a certain amount of memory space, if not released for a long time, may lead to Oom.

In C + +, it is up to the program ape to apply, manage, and free memory space, so there is no GC concept. In Java, a background dedicated to the garbage collection of a thread to monitor, scan, automatically release some useless memory, this is a basic idea of garbage collecting, the purpose is to prevent the introduction of human memory by the program ape to leak .

(2) In fact, the history of GC is longer than that of Java, and the 1960 birth of Lisp in MIT was the first language to actually use memory dynamic allocation and garbage collection techniques. When Lisp is still in embryo, people are thinking about 3 things that the GC needs to accomplish:

What memory needs to be recycled?

When do I recycle?

How to recycle?

(3) program counters, virtual machine stacks, local method stacks in the memory area the 3 regions are born with threads, the threads go out, and the stack frames in the stack execute the stack and stack operations methodically as the method enters and exits, and the amount of memory allocated to each stack frame is basically known when the class structure is determined . There is no need to think too much about recycling in these areas, 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 need memory differently, and we can only know which objects are created when the program is running. This part of the memory allocation and recycling are dynamic , the GC is concerned about this part of the memory, later in the article if the "Memory" allocation and recycling refers to only a portion of memory.

Second, the Reference counting algorithm: (Old garbage collection algorithm. Unable to process circular reference, not accepted by Java)

1, the concept of reference counting algorithm:

Add a reference counter to the object, and whenever there is a reference to it, the counter value is incremented by 1, and when the reference fails, the counter value is reduced by 1, and any object with counter 0 at any time is impossible to use again.

2. User examples:

The reference counting algorithm is simple and efficient, and is a good algorithm in most cases. Many places to apply it. For example:

Microsoft's COM technology: computer Object Model

Using ACTIONSCRIPT3 's Flashplayer

Python

However, the mainstream Java Virtual machine does not use the reference counting algorithm to manage memory, the main reason is that it is difficult to solve the problem of circular reference between objects .

3, the problem of reference counting algorithm:

    • Referencing and de-referencing accompany addition and subtraction, affecting performance
    • Fatal flaw: cannot recycle objects that are referenced by a loop

In the above 3 graphs, for the rightmost graph, the loop-referenced counters are not 0, but they are already unreachable for the root object, but they cannot be freed.

Examples of code that are circular references:

1  Public classObject {2 3Object field =NULL;4     5      Public Static voidMain (string[] args) {6Thread thread =NewThread (NewRunnable () {7              Public voidrun () {8Object objecta =NewObject ();9Object OBJECTB =NewObject ();//Location 1 ten Objecta.field = OBJECTB;  One objectb.field = objecta; // Location 2  A                 //To do something -Objecta =NULL; -OBJECTB =NULL;//Location 3 the             } -         }); - Thread.Start (); -          while(true); +     } -      +}

The above code seems a bit deliberate, but in fact, in the actual programming process, is often the case, such as two A-to-one relational database objects, each to maintain the other side of the reference. The last infinite loop is just to keep the JVM from exiting, and it doesn't really make sense.

Code Explanation:

1, 2, 33 digits are labeled in the code, and when the statement for position 1 is executed, the reference count for two objects is all 1. When the statement for position 2 is finished, the reference count of two objects becomes all 2. When the statement for position 3 is finished, that is, the reference count for both is still 1, after all the two are classified as null values. Based on the recycling rules of the reference counting algorithm, the reference count is not recycled when it is not returned to 0.

For the GC we are using now, when the thread thread finishes running, objecta and OBJECTB are all used as objects to be recycled. and if our GC uses the reference counting algorithm mentioned above, then these two objects will never be recycled , even if we display the object as null after use.

Third, root search algorithm:

1, the concept of root search algorithm:

Due to the shortcomings of the reference counting algorithm, the JVM typically uses a new algorithm called the root search algorithm . The way it is handled is to set up several root objects that can be reclaimed when any one of the root objects is unreachable to an object .

As shown, OBJECTD and objecte are interrelated, but because the GC roots to these two objects is unreachable, eventually D and E will still be treated as GC objects, and if the reference counting method is used, the A-e five objects will not be recycled.

2.

When it comes to GC roots (GC root), in the Java language, there are several objects that can be used as GC roots:

1. The referenced object in the virtual machine stack.

2. The object referenced by the class static property in the method area.

3. The object referenced by a constant in the method area.

4. The referenced object of JNI in the local method stack.

Note: The first and fourth types refer to the local variable table of the method, the second expression is clearer, and the third refers to the constant value declared final.

Based on the root search algorithm, there are three kinds of garbage collection algorithms in modern virtual machines, namely, mark-clear algorithm, copy algorithm, marker-collation algorithm. These three algorithms have expanded the root search algorithm, but they are well understood.

Four, Mark-Clear algorithm:

1. The concept of the tag clearing algorithm:

The mark-and-sweep algorithm is the basic idea of modern garbage collection algorithm. The tag-purge algorithm divides garbage collection into two phases: the tagging phase and the purge phase. A feasible implementation is to mark all the objects that can be reached from the root node, first through the root node , in the tagging phase. Therefore, objects that are not marked are garbage objects that are not referenced, and then, in the purge phase, all unmarked objects are cleared.

2, Mark-Clear algorithm Detailed:

It does this by stopping the entire program (also known as Stop the World) when the effective memory space in the heap is exhausted, and then doing two things, the first is the tag, and the second is available.

    • Tag: The process of tagging is actually traversing all GC Roots, and then marking all GC Roots objects as surviving objects.
    • Clear: The cleared process traverses all objects in the heap, erasing all unmarked objects.

That is, when the program is running, if the memory that can be used is exhausted, the GC thread is triggered and the program is paused, then the surviving object is marked again, eventually all unmarked objects in the heap are wiped out, and then the program resumes running .

Take a look at the following picture:

Represents the state of all objects during the run of the program, their flag bits are all 0(that is, unmarked, the following default 0 is unlabeled, 1 is marked), assuming that the effective memory space is exhausted , the JVM will stop the application running and turn on the GC thread, And then start tagging work, following the root search algorithm, after marking the object's state as:

As can be seen in the root search algorithm, all objects that are accessible from the root object are tagged in order to survive, and the first stage tag has been completed. Next, the second phase cleanup is performed, and after the cleanup, the remaining objects and the state of the objects are as follows:

As you can see, objects that are not tagged will be reclaimed and erased, and tagged objects will be left, and the marker bits will be returned to 0. Needless to say, wake up the stopped program thread and let the program continue to run.

Question: Why do you want to stop the program from running?

For:

This is really not difficult to understand, assuming that our program and GC threads are running together, you can imagine such a scenario.

Let's say we just tagged the rightmost object in the graph, and for the moment, a, the result is a new object B in the program, and a object can reach the B object. But because the a object is already marked at this point, the B object's marker bit is still 0, because it misses the mark stage. So when the next turn to the purge phase, the new object B will be forced to remove the hard. In this way, it is not difficult to imagine the result that GC threads will cause the program not to work correctly.

The above result is of course unacceptable, we just new an object, the result after a GC, suddenly become null, how to play?

3. The disadvantage of the tag-purge algorithm:

(1) First, its disadvantage is low efficiency (recursive and full heap object traversal), and in the GC, the need to stop the application, which will lead to a poor user experience, especially for interactive applications is simply unacceptable. Imagine, if you play a site, this site one hours to hang five minutes, you still play?

(2) The 2nd major drawback, it is this way to clean up the free memory is not continuous , this is not difficult to understand, our death objects are immediately appear in the memory of each corner, now remove them, the layout of the memory will naturally be messy. To cope with this, the JVM has to maintain a free list of memory, which is another overhead. And when allocating array objects, it's not easy to find contiguous memory space.

Five, Replication algorithm: (New generation of GC)

The concept of a replication algorithm:

Divide the original memory space into two blocks, one at a time, and at garbage collection, copy the surviving objects in the memory being used into the unused block of memory, then clear all objects in the memory block in use, swap the two memory roles, and complete the garbage collection.

    • Compared with the tag-purge algorithm, the replication algorithm is a relatively efficient recovery method
    • Not suitable for situations where there are many surviving objects, such as the old age (Replication algorithm is appropriate for the new generation of GC)

    • The biggest problem with the replication algorithm is that space is wasted

The copy algorithm makes the memory recovery only for the whole half area, and the memory allocation does not take into account the complexity of memory fragmentation, as long as the top pointer is moved, the memory can be allocated sequentially, the implementation is simple, and the operation is efficient. Just the cost of this algorithm is to reduce the memory to half the original, this is too deadly.

So from the above description is not difficult to see, the replication algorithm to use, at least the survival rate of the object is very low, and most importantly, we have to overcome 50% of memory waste.

Today's commercial virtual machines are using this collection algorithm to reclaim the new generation, the new generation of object 98% is "to die", so do not need to divide the memory space according to the ratio of 1:1, but the memory is divided into a larger Eden space and two smaller survivor space , using Eden and one piece of survivor at a time. When recycled, the objects that are still alive in Eden and survivor are copied one at a time into another survivor space, finally clearing up Eden and the survivor space just used. The default Eden and survivor size ratios for the hotspot virtual machine are 8:1, which means that the available memory space for each Cenozoic is 90% (80%+10%) of the total Cenozoic capacity, and only 10% of the space is wasted.

Of course, 98% of the objects can be recycled only in the general scenario of data, we have no way to ensure that only a few more than 10% of the object to survive, when the survivor space is not enough, we need to rely on the old age to allocate security, so large objects directly into the old age . The entire process is as follows:

, the position of the green arrow represents a large object, and the large object goes directly into the old age.

According to the above replication algorithm, now we look at the following the GC log number, you should be able to understand it:

In the GC log above, the new generation of free space is 13824K (1536K of 12288k+from space in the Eden area). According to the memory address calculation, the new generation of total space is 15M, and this 15M of space is = 13824K of +to space 1536K.

Vi. marking-Sorting algorithm: (GC of the old age)

Introduced:

If you have more replication operations when the object has a higher survival rate, the efficiency will be reduced. What's more, if you don't want to waste 50% of your space, you'll need extra space for the allocation guarantee to cope with the extreme situation where all objects in the memory being used are 100% alive, so you can't select this algorithm directly in the old age.

Concept:

The tag-compression algorithm is suitable for applications where there are many surviving objects, such as the old age. It does some optimizations based on the mark-and-sweep algorithm. Like the mark-and-sweep algorithm, the tag-compression algorithm first needs to start with the root node and mark all objects that can be reached. However, it does not simply clean up unmarked objects, but instead compresses all the surviving objects to one end of the memory. After that, clean up all the space outside the boundary.

    • Tag: Its first phase is exactly the same as the mark/Purge algorithm, which iterates through GC Roots and then marks the surviving object.
    • Organize: Move all surviving objects, arrange them in the order of memory addresses, and then reclaim all memory after the end memory address. Therefore, the second stage is called the finishing phase.

It can be seen that the tagged surviving objects will be sorted, sorted by memory address, and unmarked memory will be cleared out. As a result, when we need to allocate memory to a new object, the JVM only needs to hold the starting address of one memory, which is a lot less expensive than maintaining a free list.

The labeling/sorting algorithm can not only compensate for the shortcomings of the memory area dispersion in the mark/purge algorithm, but also eliminate the high cost of half-memory in the replication algorithm.

    • However, the only disadvantage of the tag/grooming algorithm is that it is inefficient.

Not only do you want to tag all the surviving objects, but also tidy up the reference addresses of all the surviving objects. In terms of efficiency, the labeling/sorting algorithm is lower than the copy algorithm.

A summary of the tag-purge algorithm, the replication algorithm, and the tagging algorithm:

Three algorithms are based on the root search algorithm to determine whether an object should be recycled, and the support root search algorithm can work properly, is the syntax of variables in the scope of the relevant content. Therefore, the most fundamental way to prevent memory leaks is to grasp the scope of the variables, rather than using a C/s-a memory management approach.

When the GC thread is turned on, or when the GC process starts, they pause the application (Stop the World).

The differences are as follows: (> Indicates that the former is better than the latter, = indicates the same effect)

(1) efficiency : copy algorithm > marker/Collation Algorithm > tag/purge algorithm (the efficiency here is simply a comparison of time complexity, not necessarily the case).

(2) memory uniformity : Copy algorithm = tagging/sorting algorithm > tag/purge algorithm.

(3) Memory utilization: Mark/Defragment Algorithm = mark/clear algorithm > copy algorithm.

Note 1: You can see that the tag/purge algorithm is a relatively backward algorithm, but the latter two algorithms are built on this basis.

Note 2: time and space cannot be combined.

Seven, generational collection algorithm: (New generation of gc+ in the old age of GC)

The current GC of commercial virtual machines is the "generational collection Algorithm", which is not a new idea, but divides the memory into several blocks depending on the life cycle of the object . In general, the Java heap is divided into the new generation and the old age: the short- lived object to the new generation, longevity object to the old age .

    • A small number of objects survived, suitable for the replication algorithm : In the Cenozoic , each time the GC found a large number of objects died, only a small number of survival, then choose the replication algorithm , only a small number of surviving objects to pay the cost of replication can be completed GC.
    • a large number of objects survive, suitable for marking-cleaning/labeling-collation : In the old age , because of the high survival rate of the object and the lack of additional space to guarantee his distribution, the GC must be performed using the " mark-Clean "/"Mark-sweep" algorithm.

Note: In the old age, a small part of the object is because in the new generation of recovery, the old age to do security, come in, most of the object is because many times GC has not been recycled into the old age .

Viii. Accessibility:

All algorithms need to be able to identify a garbage object and therefore need to give a definition of accessibility.

1, the concept of accessibility:

Accessible by:

This object can be touched from the root node.

It's actually scanning from the root node, so long as the object is in the reference chain, it's accessible.

To be resurrected:

Once all references have been released, it is a resurrected state

Because the object may be resurrected in Finalize ()

To be untouchable:

After Finalize (), it may enter a non-palpable state

Untouchable objects cannot be resurrected.

To be recycled.

Example of code for the Finalize method Resurrection object:

package test03;

 

/**

* Created by smyhvae on 2015/8/19.

*/

public class CanReliveObj {

public static CanReliveObj obj;

 

//当执行GC时,会执行finalize方法,并且只会执行一次

@Override

protected void finalize() throws Throwable {

super.finalize();

System.out.println("CanReliveObj finalize called");

obj = this; //当执行GC时,会执行finalize方法,然后这一行代码的作用是将null的object复活一下,然后变成了可触及性

}

 

@Override

public String toString() {

return "I am CanReliveObj";

}

 

public static void main(String[] args) throws

InterruptedException {

obj = new CanReliveObj();

obj = null; //可复活

System.out.println("第一次gc");

System.gc();

Thread.sleep(1000);

if (obj == null) {

System.out.println("obj 是 null");

} else {

System.out.println("obj 可用");

}

obj = null; //不可复活

System.out.println("第二次gc");

System.gc();

Thread.sleep(1000);

if (obj == null) {

System.out.println("obj 是 null");

} else {

System.out.println("obj 可用");

}

}

}

We need to take note of the comments on line 14th. In the beginning, we set obj to null on the 25th line, and then execute the GC once, and I thought that obj would be recycled, not actually, because the GC would call the 11-row Finalize method, and obj would be resurrected on line 14th. The obj is then set to NULL in line 34th, and then the GC is executed once, and obj is reclaimed because the Finalize method executes only once.

Summary of the use of the Finalize method:

    • Experience: Avoid using finalize() and careless operation can cause errors.
    • Low priority, when called, indeterminate

When a GC is uncertain, it's natural to know when the Finalize method executes

    • If you want to use finalize to release resources, we can use try-catch-finally to replace it.

2, accessibility Analysis:

In the previous paragraphs of the markup-cleanup algorithm/tagging algorithm, we have been emphasizing starting from the root node, all the objects can be marked once . What does it mean to reach? Here are the explanations:

Accessibility Analysis:

From the root (GC Roots) object as the starting point, the search is traversed by a path called a "chain of reference", when an object to the GC Roots no reference chain connected (in the concept of graph theory, that is, from the GC Roots to this object is not available), it proves that this object is not available.

Objects that can be used as root (GC Roots) include:

    • The object referenced in the stack (local variable table in the stack frame)
    • Static members in the method area or objects referenced by constants (global objects)
    • The object referenced by JNI (generally referred to as the native method) in the local method stack.

Nine, Stop-the-world:

1, Stop-the-world:

A phenomenon of global pauses in Java.

Global Pause, all Java code stops , native code can execute, but cannot interact with JVM

Most of the cases are caused by GC .

A few cases are caused by other circumstances, such as dump thread, deadlock check, heap dump.

2. Why does the GC have a global pause?

For example: analogy in the party, suddenly GC to come to clean the room, party is messy, and there is a new garbage production, the room will never clean, only let everyone stop activities, to the room clean.

Moreover, if there is no global pause, it will put a heavy burden on the GC thread, the GC algorithm will increase the difficulty, GC is difficult to determine what is garbage.

3, the Stop-the-world Hazard:

Long service stop, no response

Encountering an HA system can cause primary and standby switching, seriously compromising the production environment.

Note: Ha:high Available, high availability cluster.

such as the above host and standby machine: Now is the host in the work, at this time if the host is the GC caused a long pause, then the standby machine will be monitoring the host is not working, so the standby machine began to work, but the host does not work only temporarily, when the GC is over, the host began to work again, so that, The host and the standby are working at the same time. both the host and the standby are very dangerous , and are likely to result in inconsistent applications, inability to provide normal service, and thus affect the production environment.

code example:

(1) Print the Log code: (every 100ms printing one)

public static class PrintThread extends Thread{

public static final long starttime=System.currentTimeMillis();

@Override

public void run(){

try{

while(true){

long t=System.currentTimeMillis()-starttime;

System.out.println("time:"+t);

Thread.sleep(100);

}

}catch(Exception e){

 

}

}

}

In the above code, the code responsible for printing the log is printed every 100ms, and the printed time is calculated.

(2) Worker thread Code: (worker thread, dedicated to consuming memory)

public static class MyThread extends Thread{

HashMap<Long,byte[]> map=new HashMap<Long,byte[]>();

@Override

public void run(){

try{

while(true){

if(map.size()*512/1024/1024>=450){ //如果map消耗的内存消耗大于450时,那就清理内存

System.out.println("=====准备清理=====:"+map.size());

map.clear();

}

 

for(int i=0;i<1024;i++){

map.put(System.nanoTime(), new byte[512]);

}

Thread.sleep(1);

}

}catch(Exception e){

e.printStackTrace();

}

}

}

We then set the GC parameters to:

-Xmx512M -Xms512M -XX:+UseSerialGC -Xloggc:gc.log -XX:+PrintGCDetails -Xmn1m -XX:PretenureSizeThreshold=50 -XX:MaxTenuringThreshold=1

Print the log as follows:

, the red font represents the GC in progress. As a matter of principle, it should be printed every 100ms a log, but when performing GC, there will be a social pause, resulting in no time output.

In the next article, we'll cover a variety of garbage collectors.

Java Virtual Machine detailed----GC Algorithms and types

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.