Java's garbage collection mechanism

Source: Internet
Author: User

The Java language Specification does not explicitly describe which garbage collection algorithm the JVM uses, but any garbage collection algorithm typically does 2 basic things:

(1) Finding useless information objects;

(2) Reclaim the memory space occupied by the useless object, so that the space can be reused by the program.

But the garbage collector knows only the memory space that is allocated through new, and it does not know how to release this "special" area of memory. Special areas such as:

1) It is possible to use a C-like approach when allocating memory, rather than the usual new approach to Java. This occurs primarily in native method, such as native method, which calls the C + + methods malloc () function family to allocate storage space, but these memory spaces will not be freed unless the free () function is called. Then this can cause a memory leak. However, because the free () method is a function in C + +, the local method can be used to invoke it in Finalize (). To release these "special" memory spaces.

2) or open file resources, these resources are not part of the garbage collector's recycling scope.

First, garbage collection algorithm

1. Reference counting method (Reference counting Collector)

Use reference counters to differentiate between surviving objects and objects that are no longer in use. In general, each object in the heap corresponds to a reference counter. When an object is created and assigned to a variable each time, the reference counter is set to 1. When an object is assigned to any variable, the reference counter is incremented by 1 each time, and when the object is scoped (the object is discarded), the reference counter is reduced by 1, and once the reference counter is 0, the object satisfies the garbage collection condition.
A garbage collector based on a reference counter runs faster and does not interrupt program execution for long periods of time, and it is appropriate to run programs in real time. But the reference counter increases the cost of executing the program because each time the object is assigned to a new variable, the counter adds 1, and each time the existing object is scoped, the counter is reduced by 1.

2. Tracing algorithm (tracing Collector)

The tracing algorithm is proposed to solve the problem of the reference counting method, which uses the concept of the root set. The garbage collector based on the tracing algorithm starts scanning from the root set to identify which objects are available, which objects are unreachable, and to mark objects in some way, such as setting one or more bits for each object that can be reached. During the scan recognition process, garbage collection based on the tracing algorithm is also known as the Mark and Purge (mark-and-sweep) garbage collector

Note: Most garbage collection algorithms use the concept of root set (root set), which is a collection of reference variables (including local variables, parameters, class variables) that are accessible to the executing Java program. Garbage collection first needs to determine which are accessible from the root and which are unreachable, objects that can be reached from the root set are active objects, and they cannot be recycled as garbage, which also includes objects that can be reached indirectly from the root set. The root set, which is unreachable by any path, is eligible for garbage collection and should be recycled.

3. Compacting algorithm (compacting Collector)

To solve the problem of heap fragmentation, garbage collection based on tracing absorbs the idea of the compacting algorithm, in which the algorithm moves all objects to one end of the heap, and the other end of the heap becomes an adjacent free memory area, and the collector updates all references to all objects it moves. This allows these references to recognize the original object in the new location. In the implementation of the collector based on the compacting algorithm, the handle and the handle table are generally added.

4. Copying algorithm (coping Collector)

The algorithm is proposed to overcome the overhead of the handle and to solve the garbage collection of heap fragments. It begins by dividing the heap into an object area and multiple idle areas, where the program allocates space for objects from the object area, and when the object is full, garbage collection based on the coping algorithm scans the active object from the root set and copies each active object to the idle area (so that there is no idle interval between the memory occupied by the active object). The idle area becomes the object area, the original object area becomes the idle area, and the program allocates memory in the new object area.
A typical garbage collection based on coping algorithm is the stop-and-copy algorithm, which divides the heap into object and idle regions, and the program suspends execution during the switching between the object area and the idle area.

5. generation algorithm (generational Collector)

One drawback of the stop-and-copy garbage collector is that the collector must replicate all active objects, which increases the program wait time, which is why the coping algorithm is inefficient. In the program design there is such a law: most objects exist for a short time, a few of the existence of a long time. Therefore, the generation algorithm divides the heap into two or more, each sub-heap as the object's generation (generation). Because most objects exist for a shorter time, the garbage collector collects these objects from the youngest child heap as the program discards objects that are not used. After the generational garbage collector runs, the last surviving object is moved to the next highest generation sub-heap, saving time because the old generation of sub-heaps is not often recycled.

6. Adaptive algorithm (Adaptive Collector)
In certain cases, some garbage collection algorithms are better than other algorithms. The garbage collector based on the adaptive algorithm monitors the usage of the current heap and will select the appropriate algorithm for the garbage collector.

Second, trigger the main GC (garbage Collector) conditions

1) When the application is idle, the GC is called when no application thread is running. Because the GC is in the lowest priority thread, the GC thread is not called when the application is busy, except for the following conditions.

2) When the Java heap is low on memory, the GC is called. When the application thread is running and a new object is created during the run, if there is not enough memory space, the JVM will forcibly invoke the GC thread to reclaim the memory for the new allocation. If the GC still fails to meet the memory allocation requirements after one time, the JVM will take another two GC for further attempts, and if it still fails to meet the requirements, the JVM will report an "out of memory" error and the Java application will stop.

Since the main GC is determined by the JVM in terms of the system environment, and the system environment is constantly changing, the main GC runs with uncertainty and cannot predict when it will inevitably occur, but it can be determined that for a long-running application, its main GC is repeated.

Iii. reduction of waste

  Although there is a GC mechanism, but the GC itself will bring some overhead, so we are in principle to reduce garbage and reduce the frequency of GC, the main measures are as follows:

1, try not to rely on System.GC ()

  Calling System.GC () is also just a request (recommended). After the JVM accepts this message, it does not immediately do garbage collection, but only a few garbage collection algorithms are weighted, so that garbage collection operations are easy to occur, or earlier, or recycled more.

2, minimize the use of temporary objects

  Temporary objects will become garbage after jumping out of function calls, and less temporary variables will be equivalent to reducing garbage generation, thus prolonging the occurrence of the second triggering condition mentioned above and reducing the chance of the main GC.

3. It is best to explicitly set NULL when the object is not used

In general, NULL objects are treated as garbage, so explicitly setting unused objects to NULL is useful for GC collectors to determine garbage, which increases the efficiency of the GC.

4. Avoid using string to accumulate strings

As STR5=STR1+STR2+STR3+STR4, this statement produces multiple garbage objects during execution, because a new string object must be created for the "+" operation, but these transition objects are meaningless to the system and only add more garbage. Avoid this situation can use StringBuilder to accumulate the string, because the StringBuilder is variable long, it expands on the original basis, does not produce intermediate objects.

5, can use basic type such as Int,long, do not Integer,long object

A basic type variable consumes much less memory resources than the corresponding object, and it is best to use basic variables if it is not necessary.

6. Use static object variables as little as possible

Static variables are global variables, are not recycled by GC, and they always consume memory.

7. When to create or delete a dispersion object

Concentrating on creating new objects in a short amount of time, especially large objects, can result in a sudden need for a lot of memory, and in this case the JVM can only perform a primary GC to reclaim memory or consolidate memory fragments, thereby increasing the frequency of the main GC. The same is true for deleting objects centrally. It makes a large number of garbage objects suddenly appear, and the free space inevitably decreases, which greatly increases the chance of forcing the main GC the next time the new object is created.

Reference Original: http://blog.csdn.net/zsuguangh/article/details/6429592/

Java's garbage collection mechanism

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.