search
HomeJavajavaTutorialJava explains garbage collection and object life cycle in detail

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:
         Try to make the object comply with garbage collection standards in a timely manner. For example myObject = null.
         Do not use an inheritance hierarchy that is too deep.
        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:

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

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);
}

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);  
    }

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();  
   }

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

                                The finalize method has been executed.

                           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!

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
How does the class loader subsystem in the JVM contribute to platform independence?How does the class loader subsystem in the JVM contribute to platform independence?Apr 23, 2025 am 12:14 AM

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

Does the Java compiler produce platform-specific code? Explain.Does the Java compiler produce platform-specific code? Explain.Apr 23, 2025 am 12:09 AM

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

How does the JVM handle multithreading on different operating systems?How does the JVM handle multithreading on different operating systems?Apr 23, 2025 am 12:07 AM

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

What does 'platform independence' mean in the context of Java?What does 'platform independence' mean in the context of Java?Apr 23, 2025 am 12:05 AM

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Can Java applications still encounter platform-specific bugs or issues?Can Java applications still encounter platform-specific bugs or issues?Apr 23, 2025 am 12:03 AM

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

How does cloud computing impact the importance of Java's platform independence?How does cloud computing impact the importance of Java's platform independence?Apr 22, 2025 pm 07:05 PM

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

What role has Java's platform independence played in its widespread adoption?What role has Java's platform independence played in its widespread adoption?Apr 22, 2025 pm 06:53 PM

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

How do containerization technologies (like Docker) affect the importance of Java's platform independence?How do containerization technologies (like Docker) affect the importance of Java's platform independence?Apr 22, 2025 pm 06:49 PM

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.