Garbage collector and memory allocation policy Article one: A brief overview and garbage collection algorithm

Source: Internet
Author: User

I. Understanding the meaning of garbage collection

After more than half a century of development, the current memory dynamic allocation and memory recovery technology has been quite mature, everything seems to have entered the "era of automation", then why we have to study and to understand the GC and memory allocation. The answer is simple: when you need to troubleshoot various memory overflows, memory leaks, and when garbage collection becomes a bottleneck for the system to reach higher concurrency, we need to implement the necessary monitoring and tuning of these automated technologies.

Second, how to determine whether the object can be recycled

1. Reference counting method

The reference counting method is to add a reference counter to the object, and whenever there is a place to reference it, the counter value is incremented by 1, and when the reference fails, the value of the counter is reduced by 1, and any time the counter has a value of 0 is not available. Objectively speaking, the reference counting method is simple, the decision efficiency is high, in the large department of the situation below is a good algorithm, in the Python language is used, but the Java virtual machine is not using this algorithm to manage memory, because it is the solution to the problem of circular reference between objects.

Here is a set of code cases to illustrate:

Operation Result:

[gc[defnew:2884k->441k (4928K), 0.0048536 secs] 2884k->2489k (15872K), 0.0049418 secs] [times:user=0.02 sys=0.00, real=0.00 secs]

[Full gc[tenured:2048k->439k (10944K), 0.0056467 secs] 4537k->439k (15872K), [perm:1678k->1678k (12288K)], 0.0057194 secs] [times:user=0.00 sys=0.00, real=0.01 secs]

Heap

def New Generation Total 4992K, used 180K [0x04800000, 0x04d60000, 0x09d50000)

Eden Space 4480K, 4% used [0x04800000, 0x0482d370, 0x04c60000)

From space 512K, 0% used [0x04c60000, 0x04c60000, 0x04ce0000)

To space 512K, 0% used [0x04ce0000, 0x04ce0000, 0x04d60000)

Tenured generation total 10944K, used 439K [0x09d50000, 0x0a800000, 0x14800000)

The space 10944K, 4% used [0x09d50000, 0X09DBDF30, 0x09dbe000, 0x0a800000)

Compacting Perm Gen Total 12288K, used 1685K [0x14800000, 0x15400000, 0x18800000)

The space 12288K, 13% used [0x14800000, 0x149a5588, 0x149a5600, 0x15400000)

No shared spaces configured.

ERROR:JDWP unable to get JNI 1.2 environment, JVM->GETENV () Return code = 2

JDWP Exit Error Agent_error_no_jni_env (183): [.. /.. /.. /SRC/SHARE/BACK/UTIL.C:838]

You can see that the memory has changed before and after the GC, proving that the Java virtual machine is not using the reference counting method.

2. Accessibility Analysis algorithm

The basic idea of the Accessibility analysis algorithm is: from a root node as the starting point, and then from the root node search down, the path of the search to become a reference chain, when an object arrives at the root node does not have any reference chain connected, that is, the object is unreachable, it proves that the object is not available, the GC will be memory recycling.

such as GC roots as the root node, object Object5, OBJECT6, OBJECT7, although there is an association between, but because he and GC roots unreachable, so is determined to be recyclable objects.

3. Concept notes cited in four

Strong reference: Refers to a general existence in program code, similar to Object obj = new object () such a reference, as long as a strong reference exists, the garbage collector is never recyclable objects.

Soft references: is used to describe some objects that are also useful but not necessary. For objects associated with soft references, this type of object will be recycled two times before a memory overflow exception occurs in the system. If there is not enough memory after two recoveries, a memory overflow exception will be thrown.

Weak references: Also used to describe non-essential objects, but his strength is only weaker than soft references, the referenced objects only survive until the next garbage collection occurs. These weak reference objects are reclaimed when the garbage collector is working, regardless of whether the memory is sufficient.

Virtual reference: He is the weakest kind of citation relationship. Whether an object has a virtual reference exists, does not have any effect on its lifetime, nor can it obtain an object instance through a virtual reference. The sole purpose of setting a virtual reference for an object is to receive a system notification when the object is reclaimed by the garbage collector.

4. The survival or death of an object

Even if the accessibility analysis algorithm is unreachable, it is not a non-dead object. To declare an object to die two times the marking process: If the object finds no reference chain connected to the GC roots after the accessibility analysis, then he is first tagged and filtered, and the condition is that the secondary object is required to execute the Finalize () method. When the object does not overwrite the Finalize () method or the Finalize () method has been executed by the virtual machine, the virtual machine treats the 2 cases as unnecessary. The Finalize () method is only called once by the system.

If the object is judged to be necessary to execute the Finalize () method, then the object will be placed in a queue called f-quequ, and a virtual machine automatically establishes a low-priority finalize () thread to execute it later. The so-called execution means that the virtual opportunity triggers this method, but does not promise to wait for his execution to end, because if an object executes slowly in the Finalize () method, or if a dead loop occurs, it is likely to cause other objects in the F-queue queue to wait forever. It even causes the entire memory recovery system to crash. The Finalize () method is the last chance for an object to escape the fate of death, and later the GC will mark the objects in the F-queue queue for a second time, and if the object can be linked back to any object in the reference chain, it will succeed in saving itself. For example, assign yourself (the This keyword) to a class variable or to a property of your own member variable. Then he will be removed from the collection that is about to be collected the second time it is marked, but if this phase is not removed from the collection that is about to be recycled, then he is basically recycled.

This is illustrated by the following instance code:

Package Com.gc.demp;public class FIANLIZEESCAPEGC {public static FIANLIZEESCAPEGC save_sign = null;         public void IsAlive () {System.out.println ("Yes, I am still Alive"); } protected void Finalize () throws throwable{//Call the Finalize method to be called only once by the system super.                   Finalize ();             System.out.println ("Finalize Method executed");         Assigning yourself to class variables in finalize can save yourself fianlizeescapegc.save_sign = this;                   public static void Main (string[] args) throws Exception {save_sign = new fianlizeescapegc ();                   Because the Finalize method is only called once by the system, the first rescue succeeds save_sign = null;                   System.GC ();                    Because the priority of finalize is low, pause for 0.5 seconds to wait for him to Thread.Sleep (500);                    if (save_sign!=null) {save_sign.isalive (); }else {System. OUT.PRINTLN ("No, I am dead");                   }//This code is the same as above but failed the second time save_sign = null;                   System.GC ();                    Because the priority of finalize is low, pause for 0.5 seconds to wait for him to Thread.Sleep (500);                     if (save_sign!=null) {save_sign.isalive ();                    }else {System.out.println ("No, I am dead"); }         }}

Operation Result:

Special instructions are required. The Finalize () method is the beginning of the birth of Java for C + + programmers in order to accept him as a compromise, he runs a high cost, not recommended to use it to save the object.

5. Recovery method Area

The Main method area is to reclaim some obsolete constants and useless classes.

Criteria for judging 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 the method of accessing the class can no longer be accessed by reflection anywhere else.

Virtual machines can reclaim useless classes that meet the above criteria.

Iii. how the hotspot initiates memory recycling

Https://www.cnblogs.com/jing99/p/6071808.html

Four, garbage collection algorithm:

1. Tag Cleanup algorithm

The most basic algorithm is the tag cleanup algorithm. The tag cleanup algorithm is divided into two stages, marking and purging phases. First, all objects that need to be reclaimed are marked at first, and all tagged objects are reclaimed uniformly after the tag is complete. The reason that he is the most basic algorithm, that is because the subsequent collection algorithm is based on this idea and to improve its shortcomings. His shortcomings are mainly two: one is the efficiency problem, the labeling and elimination of two processes is not efficient; the other is the space

2. Copying algorithms

To solve the efficiency problem, a collection algorithm called replication appears, and he divides the available memory by capacity into two blocks of the same size, using only one piece at a time. When this piece of memory is used up, copy the surviving object to the other, and then clean up the used memory space once. This makes it possible for the entire half of the memory to be reclaimed each time, and memory allocations do not have to take into account the complexity of memory fragmentation issues.

Cons: Reduce the memory to half the original and the memory is smaller. If you don't want to waste 50% of your space, you need extra space to vouch for the extreme situation where object 100% in Object memory survives.

Pros: Do not consider space debris issues.

3. Marker Finishing Algorithm

According to the characteristics of the old age, a labeling algorithm is proposed.

The tagging process is the same as the markup cleanup process, but the next step is not to directly clean up the recyclable objects, but rather to have all the surviving objects move like a paragraph, and then directly clean out the memory outside the end boundary.

4. Collection of Generations

Divides the memory into chunks based on the different lifetime of the object. 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 new generation, a large number of objects die every day, only a small number of survival, then the use of replication algorithm. The survival rate is high in the old age, and there is no extra room for him to vouch for, and he must be collected using a tag cleanup or a tagging algorithm.

Garbage collector and memory allocation policy Article one: A brief overview and garbage collection algorithm

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.