2.6. Java memory management and garbage collection

2.6.1. Java memory model

In Java, memory is divided into the following areas:

  1. Heap (Heap): stores object instances and arrays, and is the main area for garbage collection.
  2. Stack: Stores local variables and method calls. Each thread has its own stack.
  3. Method Area: store class information, such as class structure, methods, fields, etc.
  4. Native Method Stack: Stores calls of native methods (such as JNI).
  5. Program Counter Register: Indicates the bytecode instructions executed by the current thread.

2.6.2. Java object life cycle

The life cycle of a Java object is divided into the following stages:

  1. CREATE: Use newthe keyword to create an object instance.
  2. Use: The object is referenced and used by the program.
  3. Unreachable: The object does not have any references to it and cannot be accessed by the program.
  4. Garbage collection: The garbage collector reclaims the memory occupied by unreachable objects.
  5. Memory release: The memory is freed and returned to the system.

2.6.3. Garbage Collection

Java's garbage collector automatically reclaims objects that are no longer in use. The purpose of garbage collection is to release memory occupied by useless objects and avoid memory leaks. The garbage collection process mainly occurs in the heap memory area.

How the garbage collector works:

  1. Marking: The garbage collector finds all unreachable objects and marks them as garbage.
  2. Clear: The garbage collector reclaims the memory occupied by the marked objects.

Garbage collection algorithms commonly used in Java:

  1. Reference counting method: Each object maintains a reference count. When the reference count is 0, the object is regarded as garbage. But this approach cannot solve the circular reference problem.
  2. Mark-Sweep (Mark-Sweep): It is divided into two phases of marking and clearing. The marking phase marks all unreachable objects, and the clearing phase reclaims their memory. But memory fragmentation may occur.
  3. Mark-Compact: On the basis of mark-clear, organize the surviving objects to one end of the memory, and reclaim the memory outside the boundary. Fixed memory fragmentation issue.
  4. Generational Collection: Divide the heap memory into the new generation and the old generation, and adopt different garbage collection strategies for different generations. The new generation uses the copying algorithm (Copying), and the old generation uses the mark-sweep or mark-compact algorithm.

2.6.4. Memory leaks and memory overflows

  1. Memory leak: An object in the program is no longer used, but is still referenced, making it impossible to be reclaimed by the garbage collector. Memory leaks can lead to out-of-memory.
  2. Memory overflow: The memory requested by the program exceeds the maximum memory that the system can allocate, causing the program to crash.

Ways to avoid memory leaks:

  1. Promptly release object references that are no longer in use.
  2. Avoid static collection classes referencing long-term memory-occupied objects.
  3. Use weak reference types such as WeakReference and SoftReference.

2.6.5. Examples

The following example shows a simple class, its instantiation process, and the triggering of garbage collection.

public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {
        Student student1 = new Student("Alice", 20); // 创建一个Student实例
        Student student2 = new Student("Bob", 22); // 创建另一个Student实例

        student1 = student2; // student1引用指向student2,此时原先的"student1"实例无法访问,成为垃圾

        System.gc(); // 建议JVM进行垃圾回收(注意:这并不保证立即进行垃圾回收)
    }
}

In this example, we create two Studentinstances. When student1the reference points to student2it, the original student1instance becomes unreachable and becomes garbage. We use System.gc()the recommended JVM for garbage collection. It should be noted that System.gc()garbage collection is not guaranteed immediately, and the specific timing of garbage collection depends on the implementation of the JVM.

In this section, we explain in detail the relevant knowledge of Java memory management and garbage collection, including memory model, object life cycle, garbage collection principles and algorithms, memory leaks and memory overflows, etc. We also show garbage collection triggering with a simple example. Hope this helps, and if you have any other questions, please feel free to ask.

file

file

Recommended reading:

https://mp.weixin.qq.com/s/dV2JzXfgjDdCmWRmE0glDA

https://mp.weixin.qq.com/s/an83QZOWXHqll3SGPYTL5g

Guess you like

Origin blog.csdn.net/u010671061/article/details/130946373