Java----Java garbage collection algorithm

Source: Internet
Author: User
Tags compact object object

1. Reference counting method (Reference counting Collector)

1.1 Algorithm Analysis

The reference count is an early policy in the garbage collector. In this approach, each object instance in the heap has a reference count. When an object is created and the object instance is assigned to a variable, the variable count is set to 1. When any other variable is assigned a reference to this object, the count is incremented by 1 (a = B, then the counter of the object instance referenced by B + 1), but when a reference to an object instance exceeds the life cycle or is set to a new value, the reference counter of the object instance is reduced by 1. Any object instance that references a counter of 0 can be garbage collected. When an object instance is garbage collected, the reference counter of any object instance it references is reduced by 1.

1.2 Advantages and Disadvantages

Advantages:

The reference count collector can be executed very quickly and interleaved in the program's running. It is advantageous to the real-time environment that the program needs not to be interrupted for a long time.

Disadvantages:

A circular reference could not be detected. If the parent object has a reference to a child object, the child object in turn references the parent object. In this way, their reference count will never be 0.

The 1.3 Reference counting algorithm does not resolve circular reference problems, such as:

 Public class Main {    publicstaticvoid  main (string[] args) {        new MyObject ();         New MyObject ();                   = object2;         = Object1;                   NULL ;         NULL ;    }}

The last two sentences assign Object1 and object2 null, which means that Object1 and Object2 object are no longer accessible, but because they reference each other and cause their reference counters to be 0, the garbage collector never recycles them.

2.mark-sweep (Mark-Clear) Tracing Collector ( Tracing Algorithm )

This is the most basic garbage collection algorithm, the reason is that it is the most basic because it is the easiest to achieve, the idea is the simplest. The tag-purge algorithm is divided into two stages: the tagging phase and the purge phase. The task of the tagging phase is to mark out all objects that need to be recycled, and the purge phase is to reclaim the space occupied by the tagged objects. The exact process is as follows:

It is easy to see that the tag-purge algorithm is easier to implement, but one of the more serious problems is that it is prone to memory fragmentation, and too many fragments can cause the subsequent process to allocate space for large objects without finding enough space to trigger a new garbage collection action ahead of time.

3.Copying (copy) algorithm

In order to solve the defect of mark-sweep algorithm, the copying algorithm is proposed. It 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 used up, copy the surviving object to another piece, and then clean up the used memory space once, so the memory fragmentation problem is not easy. The exact process is as follows:

This algorithm is simple, efficient, and not prone to memory fragmentation, but it has a high cost of using memory space because it can use less memory than half the original.

Obviously, the efficiency of the copying algorithm is very much related to the number of surviving objects, if there are many surviving objects, then the efficiency of the copying algorithm will be greatly reduced.

4.mark-compact (marker-collation) algorithm

In order to solve the defect of copying algorithm and make full use of memory space, the mark-compact algorithm is proposed. The algorithm marks the same stage as Mark-sweep, but after the token is completed, it does not clean the recyclable object directly, but instead moves the surviving object to one end and then cleans up memory outside the end boundary. The exact process is as follows:

  

5.Generational Collection (generational collection) algorithm

The generational collection algorithm is the algorithm used by most of the JVM's garbage collectors today. Its core idea is to divide the memory into several different regions based on the life cycle of the object's survival. In general, the heap zoning is divided into the old age (tenured Generation) and the New Generation (young Generation), the characteristics of the old age is that each garbage collection only a small number of objects need to be recycled, and the new generation is characterized by a large number of objects to be recycled each time the garbage collected, Then we can take the most suitable collection algorithm according to the characteristics of different generations.

At present, most of the garbage collectors take the copying algorithm for the new generation, because each garbage collection in the Cenozoic has to reclaim most of the objects, that is, the number of operations that need to replicate is less, but the actual is not in accordance with the ratio of 1:1 to divide the new generation of space, In general, the Cenozoic is divided into a larger Eden space and two smaller survivor space, each time using Eden space and one of the survivor space, when recycling, Copy objects that are still alive in Eden and survivor to another survivor space, and then clean up Eden and the survivor space you just used.

Because of the characteristics of the old age is that each recycling only a small number of objects, the general use of the mark-compact algorithm.

Note that there is another generation outside the heap that is the permanent generation (permanet Generation), which is used to store class classes, constants, method descriptions, and so on. The recovery of the permanent generation mainly recycles two parts: obsolete constants and useless classes.

Garbage collector

Collectors used by Cenozoic collectors: Serial, pranew, Parallel scavenge

Old age collector used by collectors: Serial, Parallel, CMS

serial collector (copy algorithm)

The new generation of single-threaded collectors, marking and scavenging are single-threaded, with the advantage of being simple and efficient.

Serial Old collector (marker-collation algorithm)

The old age single-threaded collector, the old age version of the serial collector.

parnew Collector (stop-copy algorithm)

The new generation collector, which can be considered a multithreaded version of the serial collector, has a better performance than serial in multi-core CPU environments.

Parallel Scavenge Collector (stop-copy algorithm)

A parallel collector that pursues high throughput and uses CPUs efficiently. Throughput is typically 99%, throughput = user thread time/(user thread time +GC thread time). Suitable for background applications, such as the corresponding requirements for the interaction of the scene is not high.

Parallel Old collector (stop-copy algorithm)

Parallel scavenge collector's old version, parallel collector, throughput priority

CMS (Concurrent Mark Sweep) collector (tag-cleanup algorithm)

High concurrency, low pause, the pursuit of the shortest GC recovery pause time, high CPU consumption, fast response time, short pause time, multi-core CPU to pursue high response time selection

The execution mechanism of GC

Because objects are processed in a generational way, garbage collection areas and times are different. There are two types of GC: Scavenge GC and full GC.

Scavenge GC

In general, when a new object is generated and the Eden application space fails, the scavenge GC is triggered, GC is performed on the Eden Zone, the non-surviving objects are cleared, and the surviving objects are moved to the survivor area. Then tidy up the two districts of survivor. This method of GC is carried out on the young generation of the Eden area and does not affect the old generation. Because most objects start in the Eden area, and the Eden area is not very large, GC in the Eden area is frequent. Thus, it is generally necessary to use fast and efficient algorithms, so that Eden can be free as soon as possible.

Full GC

Organize the entire heap, including young, tenured and perm. The full GC is slower than the scavenge GC because it needs to be recycled across the heap, so you should minimize the number of complete GC times. In the process of tuning the JVM, a large part of the work is to adjust the FULLGC. The full GC may be caused by the following reasons:

1. The old generation (tenured) was written full

2. Persistent generation (Perm) is fully written

3.SYSTEM.GC () is displayed call

4. Dynamic changes in the domain allocation policy of the heap after the last GC

Java has a GC also has a memory leak problem

Static collection classes like HashMap, vectors, etc. are most prone to memory leaks, and the lifetime of these static variables is consistent with the application, and all object objects cannot be freed because they will also be used by vectors.

 Static Vector v = new   Vector ();  for  (int  i = 1; i<100; i++ = 
    
     new 
      Object ();     V.add (o); o  = null  ;}  

In this example, there is a reference to the vector object in the code stack with reference to the V and object o. In the For loop, we constantly generate new objects, add them to the Vector object, and then empty the O reference. The question is, if a GC occurs when the O reference is empty, can we create an object that is recycled by GC? The answer is in the negative. Because, when the GC traces a reference in the code stack, it discovers a V reference, and continues to trace, it finds that the memory space pointed to by the V reference has a reference to the object. This means that although the O reference is already empty, there are still other references to object objects that can be accessed, so the GC cannot release it. If after this loop the object object has no effect on the program, we assume that the Java program has a memory leak.

2. Various connections, database connections, network connections, IO connections, etc. do not show call Close closed, not being garbage collected by GC causing a memory leak.

3. The use of listeners can also cause memory leaks if the object is freed without a corresponding delete listener.

Java----Java garbage collection algorithm

Related Article

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.