Java explains garbage collection and object lifecycle

  • 2020-05-30 20:08:00
  • OfStack

Java garbage collection and object lifecycle details

Garbage collection and object lifecycle in Java

1. Garbage collection

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

Once an object is created, it is placed in JVM's heap memory, and when the object is never referenced again, it is reclaimed by JVM in the heap memory. Objects created cannot be regenerated, 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 in the class and local reference fields. JVM indexes objects through the root collection.

Two types of memory managed by JVM are often used in Java application development: heap memory and stack memory. In simple terms, heap memory is primarily used to store objects and variables that the program creates or instantiates at run time. For example, objects created through the new keyword. Stack memory is used to store methods declared static or non-static in program code.

(1) the heap memory

When JVM is created at startup, the objects stored in the heap memory can be automatically recycled by JVM and cannot be recycled by other external means. In other words, developers cannot recycle the objects in the heap memory by adding relevant code. Heap memory is usually divided into two regions: the new object region and the old object region.

New object area: it can be subdivided into three small areas: Eden area, From area and To area. The garden of Eden area used to store the newly created object, it is like a stack, a new object is created, like a pointer to the stack in the growth of 1 sample, when the garden of Eden of objects in the area is full of JVM system will achieve accessibility testing, what are the main task is to detect object by the root collection is unreachable, these objects can be JVM recycling, and to all the active objects from the garden of Eden area copy to To area, 1 state of some object will happen at this time exchange, some objects will be transferred to From area from To area, The From region now has an object. The entire process of object migration above is controlled by JVM.

Old object area: the objects in the old object area will still have a long life cycle. Most of the junk objects in JVM system are from "short-lived" objects. After a period of time, the objects transferred into the old object area will become garbage objects. At this point, they are playing on the corresponding tag, JVM system will automatically recycling the rubbish object, suggest don't frequently forcing a system for recycling, this is because the JVM will utilize the limited system resources, prioritize recycling work, cause an unable to quickly response to a request from the client, this will affect the overall performance of the system.

(2) stack memory

Heap memory is primarily used to store objects and variables that the program creates or instantiates at run time. For example, objects created through the new keyword. Stack memory is used to store methods declared static or non-static in program code.

2. Lifecycle of objects in JVM

In the JVM running space, the entire life cycle of the object can be roughly divided into seven stages:

The creation phase; Application phase; No visible stage; Unreachable stage; Collectible stage; Termination stage; Release phase

The above seven phases constitute the complete lifecycle of the object in JVM.

(1) creation stage

In the object creation stage, the system mainly completes the object creation process through the following steps:

< 1 > Allocate storage space for objects;
< 2 > Start constructing objects;
< 3 > Initialize static members from superclass to subclass;
< 4 > The superclass member variables are initialized in order, and the superclass constructor is recursively called.
< 5 > Subclass member variables are initialized in order, and subclass constructs method calls.

A few key application rules should be noted when creating objects:

< 1 > Avoid creating objects in the body of the loop, even if they don't take up much memory.
< 2 > Try to make objects conform to garbage collection standards in a timely manner. So myObject = null.
< 3 > Do not use too deep a hierarchy of inheritance.
< 4 > Accessing local variables is better than accessing variables in a class.

(2) application phase

In the reference phase of the object, the object has the following characteristics:

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

< 2 > All references to this object are strong references (unless we explicitly apply them: soft references (Soft Reference), weak references (Weak Reference), or virtual references (Phantom Reference)).

Strong reference (Strong Reference) : means that the JVM memory manager traverses the path to all objects in the heap 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 (Soft Reference) : the main feature of soft reference is the strong reference function. This type of memory is only recycled when there is not enough memory, so it is usually not recycled when there is. In addition, these reference objects are guaranteed to be set to null before Java throws an OutOfMemory exception. It can be used to implement 1 common resources cache, implement Cache function, ensure the maximum use of memory you do not cause OutOfMemory.

Here is the implementation code for the soft reference:


                import java.lang.ref.SoftReference;
                ...
                 
                A a = new A();
                ...
 
                //  use a
                ...
                 
                //  Use up a,  Set it to soft Reference type, and release the strong reference 
                SoftReference sr = new SoftReference(a);
                a = null;
                ...
 
                //  The next time you use it 
          if (sr != null) {
          a = sr.get();
        } else {
          // GC Due to low memory, has been freed a , so it needs to be reloaded 
                  a = new A();
          sr = new SoftReference(a);
        }
 

The introduction of soft reference technology enables Java applications to better manage memory, stabilize the system, prevent system memory overflow, and avoid system crash. Therefore, this technique should be applied when dealing with objects that take up a large amount of memory and have a long life cycle, but are not very complex. Improve system stability.

Weak reference (Weak Reference) : the biggest difference between weak application object and soft reference object is that when GC is doing garbage collection, it needs to check whether Soft application object is recycled by algorithm, while for Weak reference, GC is always recycled. Weak reference objects are more easily and quickly recycled by GC. Weak reference objects are often used in Map structures.


import java.lang.ref.WeakReference;  
                ...  
                 
               A a = new A();  
               ...  
 
               //  use a  
               ...  
                 
               //  Use up a,  Set it to Weak Reference type, and release the strong reference   
               WeakReference wr = new WeakReference(a);  
               a = null;  
                ...  
               //  The next time you use it   
       if (wr != null) {  
         a = wr.get();  
      } else {  
                  a = new A();  
        wr = new WeakReference(a);  
    } 

Virtual references (Phantom Reference): virtual references are less useful and are mainly used to assist the use of finalize functions.

A virtual reference (Phantom Reference) object is an object that has completed the finalize function and is unreachable, but has not yet been reclaimed by GC. This object can assist finalize in some later stages of recovery, and we increase the flexibility of the resource recovery mechanism by overwriting Refernce's clear() method.

In the actual program design, weak reference and virtual reference are rarely used, but soft reference is more often used, because soft reference can accelerate the recovery speed of JVM to garbage memory, can maintain the security of the system operation, prevent the occurrence of memory overflow (OutOfMemory) and other problems.

(3) no visible stage

When an object is in the invisible phase, it means that we can no longer refer to it in other areas of the code, and its strong reference has disappeared, for example, the local variable is beyond its visibility
The scope of.


try {  
      Object localObj = new Object();  
  localObj.doSomething();  
   } catch (Exception e) {  
     e.printStackTrace();  
   }  
 
   if (true) {  
  //  In this area localObj  The object is no longer visible ,  The compiler will report an error.   
  localObj.doSomething();  
   } 

(4) unreachable stage

Objects in the unreachable phase are no longer strongly referenced, either directly or indirectly, in the virtual machine's root set of object references, which are generally temporary variables in all thread stacks. All static variables that have been loaded or references to local code interfaces.

(5) collectible stage, termination stage and release stage

When an object is in the collectible stage, the terminal stage and the release stage, the object has the following three conditions:

< 1 > The collector has found that the object is no longer reachable.

< 2 > The finalize method has been executed.

< 3 > Object space has been reused.

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


Related articles: