Java garbage collection mechanism

Source: Internet
Author: User

an overview1. Garbage

JVM garbage collection is aimed primarily at garbage in the heap, because when threads start allocating space in the stack, the thread ends, automatically frees up space, does not need real-time monitoring; The method area primarily stores class information and static variables and constants, usually valid throughout the entire program run, and there are no objects that need to be recycled.

garbage refers to objects that cannot be accessed by threads, an object that is visible only to threads, can be accessed by threads, is available, or is simply understood as an object without any references. Strictly speaking, there is no representation of any reference object that narrows the category of garbage , for example, in a circular reference, an object a refers to another object B, and object B refers to the reference relationship between A,a and B only exists in between, and no external object references a or B, Then A and B can not be included in the operation of the program, that is, can not be accessed by any one thread, it becomes a useless object, according to the motive of defining garbage, the object that is no longer used is garbage, A and B is naturally garbage.

Garbage is sometimes referred to as a useless object, and non-spam is called a surviving object.

2. Memory Leaks

Memory waste is a phenomenon in which useless objects continue to occupy memory, which is called memory leaks. The root cause of memory leaks is that long-life-cycle objects still hold references to short life-cycle objects, such as the following code:

     Public void test02 () {        new  Object ();        Obj.dosome (); // after calling the Dosome method in the object, the object is no longer used, but still holds the reference to the object obj         ......................     }

An object is created in the method that is created to access the method Dosome in the object, and the method accesses the object without accessing it, while the reference variable, obj, still points to the object, and since the object has a reference, the object is not considered garbage, but the object has become a useless object and should be dereferenced So that the garbage collector reclaims the memory space occupied by the object, "Obj=null;" De-Reference.

3. Memory Recovery

The garbage collector reclaims not objects, but the memory space occupied by useless objects so that space can be reused.

4. Memory Fragmentation

Small, discontinuous free space generated during memory allocation and recycling:

Because of the space to be recycled, after the reclamation is completed, the available space is divided into separate small units, because these units are small size, can not store large data, need to open up space for large data, resulting in memory waste.

two algorithm for determining garbage1. Reference counting Algorithm

When an object is created, a reference counter is added to the object whenever a variable references the object, the counter adds 1, the variable releases the reference, the counter is minus 1, and any time the counter is 0, which means that no object is referencing the object and the object is garbage.

The natural flaw of the reference counting algorithm is that the circular reference problem cannot be solved, that is, the two objects that are referenced by the loop are considered as usable objects even if they are no longer being used, and are not reclaimed by the garbage collector. The JVM garbage collection mechanism does not use this algorithm, but is the following accessibility analysis algorithm.

2. Accessibility Analysis Algorithm

The accessibility analysis algorithm uses the tracking method to determine if an object is alive, and any object that can be traced to it is a surviving object, which is not traceable, and the unreachable object is useless. The starting point of the trace is any object that is currently being accessed, starting from that object, locating the object referenced by the object, looping through it, forming a reference chain, an object that is not on the reference chain, or a garbage object that is not used by the thread. For example, a reference chain is formed on the left, and all objects on the chain are living objects, while the right object is a useless object, although there is a referential relationship between them, leaving the reference chain of the thread.

This analysis is dynamic, not static, and changes as the object reference relationship changes.

three-object storage partitioning

Different object life cycle, in order to recover memory in a timely manner, the short life cycle of objects frequently perform garbage collection operations, and the long life of the object is relatively stable, long-term existence, garbage collection scan number of fewer, so in order to save overhead, reduce garbage collection times, Store objects of different lifecycles in different areas of memory for different garbage collection strategies.

The JVM divides the object's storage space into three zones: the new generation, the old age, and the permanent generation.

1. Cenozoic

The new generation was created to quickly recover objects with short life cycles, and all newly generated objects were first placed in the Cenozoic. The Cenozoic is divided into 3 parts: Eden, from Survivor and to survivor, with a spatial ratio of 8:1:1.

The newly created object is first placed in Eden, performing multiple GC (garbage collection), and when the Eden area is full, the surviving objects are transferred to the from Survivor area, and the surviving objects are transferred to the to Survivor,to after the survivor is full. When the Surviror area was full, the surviving object was promoted to the old age.

The JVM frequently performs GC for objects in the younger generation, and most of the objects are recycled in the younger generation, with very few entering the old age.

2. The old age

The objects in the old age are the objects that survived by multiple GC, the life cycle is longer and more stable, so the number of GC operations is less.

3. Permanent Generation

A permanent generation is a method area that stores class information as well as static variables and constants, with the same life cycle as the application, which generally does not require garbage collector processing.

four garbage collection algorithm

Garbage collection algorithm is the algorithm used in the actual collection after garbage confirmation, there are 3 kinds of common algorithms:

1. Mark-Clear Method

Marking a garbage object first, and then reclaiming the memory space occupied by the object, can lead to memory fragmentation, which is basically not used.

2. Copying Algorithms

Divide the memory space into multiple regions, and garbage collection copies all the surviving objects in one region to another, then empties the zone so that no memory fragmentation occurs. The new generation garbage collection uses this algorithm, from the Eden Zone to the from Survivor area, and then to the to Survivor area, because there are fewer surviving objects and less space to replicate.

3. Labeling-Sorting algorithm

First mark the objects that need to be cleared, move all the surviving objects to one end, and then clear all the useless objects. Unlike the new generation, the old age, each GC after the survival of more objects, using the replication algorithm occupies a large amount of memory, using the "tag-collation" algorithm to save memory, without causing memory fragmentation.

Five garbage collection Opportunity

Different generations have different GC mechanisms:scavenge GC and full GC.

When the new Generation Eden region is full, the newly generated object request space fails, triggering the scavenge GC, GC manipulation of the Eden area, clearing of useless objects, and freeing up space. Scavenge GC only works for the Cenozoic.

When the old age is full or the persistent generation is full, or the System.GC () method is explicitly called, it triggers the fully GC, GC for all object storage areas, the resource is expensive, and should have less full GC times.

Vi. Other methods1.system.gc ()

tells the JVM to start the garbage collector, which uses a daemon thread and does not necessarily start immediately, and when the boot is not controlled. In addition , the resource consumption is large, generally do not explicitly call.

2.finalize ()

An object-scoped method. Called after the JVM confirms that an object cannot be accessed, it can only be called once, and is typically used to release the connection resource. After the method is called, the garbage collector does not immediately reclaim the space occupied by the object, because the object may be re-accessed during the execution of the method, but when the next GC confirms that the object is still inaccessible to reclaim the space occupied by the object.

seven measures to reduce memory leaks
    1. Avoid using static variables because the life cycle of static variables is the same as the application, even if it is not used for a long time, it still occupies memory space.
    2. Resource links, such as outputstream\inputstream\connection\socket, should be closed immediately, releasing resources in a timely manner.

Reference:

https://www.ibm.com/developerworks/cn/java/l-JavaMemoryLeak/
Http://www.cnblogs.com/andy-zcx/p/5522836.html
Http://www.cnblogs.com/yulinfeng/p/7163052.html
Http://www.cnblogs.com/laoyangHJ/archive/2011/08/17/JVM.html
http://blog.csdn.net/hudashi/article/details/52058355
http://blog.csdn.net/lu1005287365/article/details/52475957

Java 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.