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

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

Jan 17, 2017 pm 03:38 PM

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

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;
  }
Copy after login

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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles