Home > Java > javaTutorial > body text

Java explains garbage collection and object life cycle in detail

高洛峰
Release: 2017-01-17 15:50:54
Original
1494 people have browsed it

Java Detailed explanation of garbage collection and object life cycle

Garbage collection and object life cycle in Java

1. Garbage collection

Garbage collection is the memory in Java programming The core concept of management, the JVM's memory management mechanism is called the garbage collection mechanism.

After an object is created, it is placed in the heap memory of the JVM. When this object is never referenced, it will be recycled by the JVM in the heap memory. Created objects cannot be reproduced, and there is no way to release them through program statements. That is, when an object cannot be reached (found) through the root collection in the JVM runtime space, the object is called a garbage object. The root collection is composed of static reference fields and local reference fields in the class. The JVM indexes objects through the root collection.

When developing Java applications, two types of memory managed by the JVM are often used: heap memory and stack memory. Simply put, heap memory is mainly used to store objects and variables created or instantiated by the program during runtime. For example, objects created through the new keyword. The stack memory is used to store methods declared as static or non-static in the program code.

(1) Heap memory

Heap memory is created when the JVM starts. Objects stored in the heap memory can be automatically recycled by the JVM and cannot be recycled by other external means. That is to say Developers cannot reclaim objects in heap memory by adding relevant code. Heap memory is usually divided into two areas: new object area and old object area.

New object area: It can be subdivided into three small areas: Eden area, From area and To area. The Eden area is used to save newly created objects. It is like a stack. New objects are created just like the pointer to the stack is growing. When the objects in the Eden area are full, the JVM system will be reachable. The main task of the sex test is to detect which objects are unreachable from the root collection. These objects can be recycled by the JVM, and all active objects are copied from the Eden area to the To area. At this time, some objects will have state exchanges. Some objects are transferred from the To area to the From area. At this time, the From area has objects. The entire process of object migration above is controlled by the JVM.

Old object area: Objects in the old object area will still have a long life cycle. Most of the JVM system garbage objects originate from "short-lived" objects. After a period of time, they are Objects transferred to the old object area become garbage objects. At this time, they are all marked accordingly, and the JVM system will automatically recycle these garbage objects. It is recommended not to force the system to perform garbage collection frequently. This is because the JVM will use limited system resources to complete garbage collection work first, resulting in application The inability to respond quickly to requests from the user side will affect the overall performance of the system.

(2) Stack memory

Heap memory is mainly used to store objects and variables created or instantiated by the program at runtime. For example, objects created through the new keyword. The stack memory is used to store methods declared as static or non-static in the program code.

2. The life cycle of objects in JVM

In the JVM runtime space, the entire life cycle of an object can be roughly divided into 7 stages:

Creation stage ;

Application phase;

Invisible phase;

Unreachable phase;

Collectable phase;

Termination phase;

Release Phase

The above 7 stages constitute the complete life cycle of objects in the JVM.

(1) Creation phase

In the object creation phase, the system mainly completes the object creation process through the following steps: The object allocates storage space;
                                                                                                                                   Start constructing the object; Recursively call the constructor of the super class;

                                                                                                                                                                                        综合的综合法是什么意思


When creating objects, you should pay attention to several key application rules:
         <2> Try to make the object comply with garbage collection standards in a timely manner. For example myObject = null.
         <3> Do not use an inheritance hierarchy that is too deep.
        <4> Accessing local variables is better than accessing variables in the class.

(2) Application phase

In the object reference stage, the object has the following characteristics:

<1> The system maintains at least one strong reference (Strong Reference) to the object;

<2> ; All references to the object are strong references (unless we explicitly apply: Soft Reference, Weak Reference, or Phantom Reference).

Strong Reference ( Strong Reference): refers to the JVM memory manager traversing all paths to objects in the heap starting from the root reference collection. When any path to an object does not contain a reference object, the reference to the object is called a strong reference.

Soft Reference: The main feature of soft reference is its strong reference function. This type of memory is only reclaimed when there is not enough memory, so they are usually not reclaimed when there is enough memory. In addition, these reference objects are guaranteed to be set to null before Java throws an OutOfMemory exception. It can be used to cache some commonly used resources and implement the Cache function to ensure maximum use of memory without causing OutOfMemory.

The following is the implementation code of soft reference:

        import java.lang.ref.SoftReference;
        ...
          
        A a = new A();
        ...
 
        // 使用a
        ...
          
        // 使用完了a, 将它设置为soft引用类型,并且释放强引用
        SoftReference sr = new SoftReference(a);
        a = null;
        ...
 
        // 下次使用时
  if (sr != null) {
  a = sr.get();
} else {
  // GC由于低内存,已释放a,因此需要重新装载
          a = new A();
  sr = new SoftReference(a);
}
Copy after login

The introduction of soft reference technology enables Java applications to better manage memory, stabilize the system, prevent system memory overflow, and avoid system crashes. Therefore, this technology should be applied as much as possible when dealing with objects that occupy a large amount of memory and have a long life cycle, but are not used frequently. Improve system stability.

Weak Reference: The biggest difference between weak application objects and soft reference objects is that when GC performs garbage collection, it needs to use an algorithm to check whether to recycle Soft application objects, and for Weak references , GC always collects. Weak reference objects are easier and faster to be recycled by GC. Weak reference objects are often used in Map structures.

import java.lang.ref.WeakReference;  
                ...  
                  
               A a = new A();  
               ...  
  
               // 使用a  
               ...  
                  
               // 使用完了a, 将它设置为Weak引用类型,并且释放强引用  
               WeakReference wr = new WeakReference(a);  
               a = null;  
                ...  
               // 下次使用时  
       if (wr != null) {  
         a = wr.get();  
      } else {  
                  a = new A();  
        wr = new WeakReference(a);  
    }
Copy after login

Phantom Reference: Phantom Reference has fewer uses and is mainly used to assist the use of the finalize function.

Phantom Reference objects refer to some objects that have finished executing the finalize function and are unreachable objects, but have not yet been recycled by GC. This kind of object can assist finalize in some later recycling work. We have enhanced the flexibility of the resource recycling mechanism by overriding the clear() method of Reference.

In actual programming design, it is rarely used for weak references and virtual references. There are many cases of soft references, because the use of soft quotes can accelerate the recycling speed of JVM on junk memory and maintain the operation of the system. Prevent problems such as memory overflow (OutOfMemory) from occurring.

(3) Invisible stage

When an object is in the invisible stage, it means that we can no longer reference it in the code in other areas, and its strong reference has disappeared. For example, a local variable exceeds its visual
scope.

try {  
      Object localObj = new Object();  
  localObj.doSomething();  
   } catch (Exception e) {  
     e.printStackTrace();  
   }  
  
   if (true) {  
  // 此区域中localObj 对象已经不可视了, 编译器会报错。  
  localObj.doSomething();  
   }
Copy after login

(4) Unreachable stage

Objects in the unreachable stage can no longer find direct or indirect strong references in the object reference root collection of the virtual machine. These Objects are generally temporary variables in all thread stacks. All loaded static variables or references to native code interfaces.

(5) Collectable stage, final stage and release stage

When an object is in the collectable stage, final stage and release stage, the object has the following three situations:

# & lt; 1 & gt; The recyler found that the object is not available.

                                <2> The finalize method has been executed.

                           <3> The object space has been reused.

Thank you for reading, I hope it can help you, thank you for your support of this site!

For more articles on Java’s detailed explanation of garbage collection and object life cycle, please pay attention to the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!