search
HomeJavajavaTutorialIn-depth understanding of Java garbage collection mechanism and memory leaks

Preface

I saw a question on segmentfault: Java has a complete GC mechanism, so will there be memory leaks in Java, and can you give a case of memory leaks. This question view gives the complete answer to this question.

Introduction to the garbage collection mechanism

During the running of the program, every time an object is created, a certain amount of memory will be allocated to store object data. If you just keep allocating memory, the program will sooner or later face the problem of insufficient memory. Therefore, in any language, there will be a memory recycling mechanism to release the memory of expired objects to ensure that the memory can be reused.

The memory recycling mechanism can be divided into two types according to the different implementation roles. One is that the programmer manually releases the memory (such as C language) and the other is the language's built-in memory recycling mechanism. For example, this article will Introducing the java garbage collection mechanism.

Java's garbage collection mechanism

In the runtime environment of the program, the Java virtual machine provides a system-level garbage collection (GC, Carbage Collection) thread, which is responsible for recycling lost references. The memory occupied by the object. The prerequisite for understanding GC is to understand some concepts related to garbage collection. These concepts are introduced one by one below.

The state of objects in the jvm heap area

Instances of Java objects are stored in the jvm heap area. For GC threads, these objects have three states.

1. Reachable state: If there are variable references in the program, then this object is in a reachable state.

2. Resurrectable state: When no variable in the program refers to this object, then the object changes from the touchable state to the resurrectable state. The CG thread will prepare to call the finalize method of this object at a certain time (the finalize method inherits or rewrites the sub-Object). The code in the finalize method may convert the object to a touchable state, otherwise the object will be converted to an untouchable state.

3. Unreachable state: Only when the object is in an unreachable state, the GC thread can reclaim the memory of this object.

In-depth understanding of Java garbage collection mechanism and memory leaks

In order to release objects correctly, GC must monitor the running status of each object, including object application, reference, being referenced, assignment, etc. GC needs to monitor. So no matter whether an object is in any of the above states, the GC will know it.

As mentioned above, the GC thread will execute the finalize method of the resurrectable state object at a certain time, so when will it be executed? Since different JVM implementers may use different algorithms to manage GC, developers cannot predict the timing of various operations (including detecting object status, releasing object memory, and calling the object's finalize method) by the GC thread at any time. Although the GC thread can be reminded to perform garbage collection operations as soon as possible through the System.gc() and Runtime.gc() functions, there is no guarantee that the GC thread will perform the corresponding recycling operations immediately.

Memory leak

Memory leak refers to the failure of the program to release memory that is no longer used due to incorrect design, resulting in a waste of resources. GC will automatically clean up the memory occupied by objects that have lost references. However, if some objects are always referenced due to a programming error, a memory leak will occur.

For example, the following example. A stack is implemented using an array, with two operations: push and pop.

import com.sun.javafx.collections.ElementObservableListDecorator;
import com.sun.swing.internal.plaf.metal.resources.metal_sv;
 
import java.beans.ExceptionListener;
import java.util.EmptyStackException;
 
/**
 * Created by peng on 14-9-21.
 */
public class MyStack {
  private Object[] elements;
  private int Increment = 10;
  private int size = 0;
 
  public MyStack(int size) {
    elements = new Object[size];
  }
 
  //入栈
  public void push(Object o) {
    capacity();
    elements[size++] = o;
  }
 
  //出栈
  public Object pop() {
    if (size == 0)
      throw new EmptyStackException();
    return elements[--size];
  }
 
  //增加栈的容量
  private void capacity() {
    if (elements.length != size)
      return;
    Object[] newArray = new Object[elements.length + Increment];
    System.arraycopy(elements, 0, newArray, 0, size);
  }
 
  public static void main(String[] args) {
    MyStack stack = new MyStack(100);
    for (int i = 0; i < 100; i++)
      stack.push(new Integer(i));
    for (int i = 0; i < 100; i++) {
      System.out.println(stack.pop().toString());
    }
  }
}

This program is available and supports common push and pop operations. However, there is a problem that has not been handled well, that is, when popping the stack, the reference to the popped element in the array is not released. This causes the program to keep a reference to this Object (this object is referenced by the array). The GC will always think that This object is reachable, let alone releasing its memory. This is a typical case of memory leak. In response to this, the modified code is:

//出栈
  public Object pop() {
    if (size == 0)
      throw new EmptyStackException();
    Object o = elements[--size];
    elements[size] = null;
    return o;
  }

The above article on in-depth understanding of Java garbage collection mechanism and memory leaks is all the content shared by the editor. I hope it can give you a reference, and I hope you will learn more Support PHP Chinese website.

For more in-depth understanding of Java garbage collection mechanism and memory leak related articles, 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
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

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 Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

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.