Home  >  Article  >  Java  >  java--detailed explanation of garbage collection mechanism

java--detailed explanation of garbage collection mechanism

巴扎黑
巴扎黑Original
2017-07-18 18:15:431428browse

An overview

1. Garbage

JVM garbage collection mainly targets the heap Garbage in the stack, because space is allocated in the stack when the thread starts, and when the thread ends, the space is automatically released, and no real-time monitoring is required; the method area mainly stores class information and static variables and constants, which are usually valid during the entire program running, and there is no need Recycled objects.

Garbage refers to objects that cannot be accessed by threads. An object can only be used if it is visible to the thread and can be accessed by the thread. It can also be simply understood as an object without any references. Strictly speaking, the expression without any reference to the object narrows the scope of garbage. For example, in a circular reference, an object A refers to another object B, and object B refers to A, and the references of A and B The relationship only exists between the two. If no external object refers to A or B, then A and B cannot be included in the running of the program, that is, they cannot be accessed by any thread, and they become useless objects. According to the definition of garbage Motivation, objects that are no longer used are garbage, and A and B naturally belong to garbage.

Sometimes garbage is also called useless objects, and non-garbage is called live objects.

2. Memory leak

The phenomenon of useless objects continuing to occupy memory causing memory waste is called a memory leak. The root cause of memory leaks is that long-lived objects still hold references to short-lived objects after use, such as the following code:

    public void test02(){
        Object obj = new Object();
        obj.doSome();//调用了对象中的doSome方法以后,就不再使用该对象,但是依然持有对象的引用obj        ...................... 
    }

An object is created in the method. The purpose of creating the object is only to access the method doSome in the object. After the method is accessed, the object will no longer be accessed. At this time, the reference variable obj still points to the object. Since the object If there is a reference, the object will not be regarded as garbage, but the object has become a useless object and should be dereferenced so that the garbage collector can reclaim the memory space occupied by the object. "obj=null;" dereferences.

3. Memory recycling

#The garbage collector does not recycle objects, but the memory space occupied by useless objects so that the space can be recycled Use again.

4. Memory fragmentation

The small, discontinuous free space generated during the memory allocation and recycling process, as shown in the figure Display:

Since the space waiting for recycling is scattered, after the recycling is completed, the available space is divided into one by the used space. Because these units are small and cannot store large data, additional space needs to be opened for large data, resulting in a waste of memory.

Two algorithms for determining garbage

1. Reference counting algorithm

given when the object is created The object adds a reference counter. Whenever a variable refers to the object, the counter is incremented by 1. When the variable releases the reference, the counter is decremented by 1. If the counter is 0 at any time, it means that no object refers to the object and the object becomes garbage.

The inherent flaw of the reference counting algorithm is that it cannot solve the problem of circular references, that is, even if the two objects referenced by the circular are no longer used, they are still regarded as usable objects and will not be garbage Recycler recycling. The JVM garbage collection mechanism does not use this algorithm, but the following reachability analysis algorithm.

2. Reachability analysis algorithm

The reachability analysis algorithm uses tracking to determine whether the object is alive. Anything that can be tracked can be Reached objects are all alive objects, and objects that are untraceable or unreachable are useless objects. The starting point of tracking is any object that is currently being accessed. Starting from this object, find the object referenced by the object, and loop in sequence to form a reference chain. Objects that are not on the reference chain are objects that are not used by the thread and are garbage. As shown in the figure below, a reference chain is formed on the left side. All objects on the chain are alive objects. Although the objects on the right side have reference relationships with each other, they are out of the reference chain of the thread, so they are useless objects.

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

Three object storage divisions

Different objects have different life cycles. In order to recycle memory in a timely manner, garbage collection is frequently performed on objects with short life cycles. Operations, and objects with long life cycles are relatively stable and can exist for a long time. The number of garbage collection scans is small. Therefore, in order to save costs and reduce the number of garbage collections, objects with different life cycles are stored in different areas of the memory in order to use different garbage collection methods. Collection strategy.

The JVM divides the object storage space into three areas: the new generation, the old generation, and the permanent generation.

1. New Generation

The new generation is established to quickly recycle objects with short life cycles. All newly generated objects are first placed in the new generation. generation. The new generation is divided into three parts: eden, from survivor, and to survivor, with a space ratio of 8:1:1.

The newly created objects are first placed in eden, and multiple gc (garbage collection) are performed. After the eden area is full, those objects that are still alive will Will be transferred to the from survivor area. When the from survivor area is full, the surviving objects are transferred to the to survivor area. When the to surviror area is full, the surviving objects are promoted to the old generation.

The JVM frequently performs gc on objects in the young generation. Most objects will be recycled in the young generation, and a small number will enter the old generation.

2. Old generation

The objects in the old generation are all objects that have survived multiple GCs. They have a longer life cycle and are relatively Stable, so fewer gc operations are performed.

3. Permanent generation

The permanent generation is also the method area. It stores class information, static variables and constants. The life cycle is the same as that of the application, and is generally not needed. The garbage collector handles it.

Four Garbage Collection Algorithms

The garbage collection algorithm is the algorithm used for actual collection after garbage confirmation. There are three common algorithms:

1. Mark-clear method

First mark the useless objects, and then recycle the memory space occupied by the objects. This will cause memory fragmentation and is basically not used. the algorithm.

2. Copy algorithm

Divides the memory space into multiple areas. During garbage collection, all surviving objects in one area are copied to another area and then clear that area so there is no memory fragmentation. This algorithm is used during new generation garbage collection, copying from the eden area to the from survivor area, and then to the to survivor area. Because there are fewer surviving objects, less space is taken up during copying.

3. Marking-organizing algorithm

First mark the objects that need to be cleared, move all surviving objects to one end, and then clear all useless objects . Unlike the new generation, the old generation has more surviving objects after each GC, and the copy algorithm takes up a lot of memory. The "mark-organize" algorithm saves memory without causing memory fragmentation.

5 Garbage collection timing

Different generations have different gc mechanisms: Scavenge GC and Full GC.

When the new generation eden area is full and the newly generated objects fail to apply for space, Scavenge GC will be triggered to perform gc manipulation on the eden area, clear useless objects, and make space. . Scavenge GC only works on the new generation.

When the old generation is full or the persistent generation is full, or the System.gc() method is explicitly called, Full GC will be triggered to perform gc on all object storage areas and consume resources. Larger, there should be fewer Full GC times.

Six other methods

1.System.gc()

Inform the JVM to start garbage The collector and garbage collector use daemon threads and do not necessarily start immediately. The specific time when they start cannot be controlled. In addition, consumes a lot of resources, so do not call it explicitly under normal circumstances.

2.finalize()

Object scope method. Called after the JVM confirms that an object cannot be accessed, it can only be called once and is usually used to release connection resources. After this method is called, the garbage collector will not immediately reclaim the space occupied by the object, because the object may be accessed again during the execution of this method. Instead, it will only reclaim the space occupied by the object after confirming that the object is still inaccessible during the next gc. space.

Seven measures to reduce GC overhead

  1. Avoid using static variables, because the life cycle of static variables is different from that of the application Similarly, even if it is not used for a long time, it still occupies memory space.

  2. Resource connections, such as OutputStream\InputStream\Connection\Socket, should be closed immediately after use and resources released in a timely manner.

  3. Try not to explicitly call System.gc(), because this method may trigger Full GC, which is expensive.

  4. Reduce the use of temporary variables, because after the method is executed, the temporary variables become garbage. A large number of temporary variables will increase the number of gc and increase system consumption.

  5. #After the object reference is completed, release the reference in time to reclaim the memory space in time.

  6. # Try to use variable objects and reduce the number of uses of immutable objects.

  7. Try to use basic type variables instead of corresponding wrapper classes, because basic type variables occupy much fewer resources than the corresponding wrapper classes.

  8. #Scatterly create and delete objects, because centralized creation of objects requires a lot of space, which is likely to trigger Full GC and instantly increase system consumption. Deleting objects intensively may cause a large number of useless objects to appear in an instant, which may also trigger Full GC.

refer to:


     
     
     
     
     

The above is the detailed content of java--detailed explanation of garbage collection mechanism. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn