Table of Contents
Preface
Java Heap Memory
New generation
Old Generation
Permanent generation
How to determine whether an object is alive
Home Java javaTutorial Things about Java GC (1)

Things about Java GC (1)

Feb 22, 2017 am 10:08 AM

Preface

Unlike the C language, the allocation and recycling of Java memory (heap memory) is automatically completed by the JVM garbage collector. This feature is very popular and can help programmers write code better. This article takes the HotSpot virtual machine as an example to talk about Java GC.

Java Heap Memory

In the article about JVM memory, we already know that the Java heap is a memory area shared by all threads, and all object instances and arrays All memory allocation is done on the heap. In order to perform efficient garbage collection, the virtual machine divides the heap memory into three areas: Young Generation, Old Generation and Permanent Generation.

Things about Java GC (1)

New generation

The new generation consists of Eden and Survivor Space (S0, S1), and the size is specified by the -Xmn parameter. The memory size ratio between Eden and Survivor Space defaults to 8:1, which can be specified through the -XX:SurvivorRatio parameter. For example, when the new generation is 10M, Eden is allocated 8M, and S0 and S1 are each allocated 1M.

Eden: Greek, meaning the Garden of Eden. In the Bible, the Garden of Eden means paradise. According to the records in the Old Testament Genesis, God Jehovah created the first earth in his own image. A man, Adam, created a woman, Eve, from one of Adam's ribs and placed them in the Garden of Eden.

In most cases, objects are allocated in Eden. When Eden does not have enough space, a Minor GC will be triggered. The virtual machine provides the -XX:+PrintGCDetails parameter to tell the virtual machine to print when garbage collection occurs. Memory reclamation log.

Survivor: It means survivor and is the buffer area between the new generation and the old generation.

When GC (Minor GC) occurs in the new generation, the surviving objects will be moved to the S0 memory area and the Eden area will be cleared. When the Minor GC occurs again, the surviving objects in Eden and S0 will be moved to S1 memory area.

Surviving objects will repeatedly move between S0 and S1. When the object moves from Eden to Survivor or between Survivors, the GC age of the object automatically accumulates. When the GC age exceeds the default threshold of 15, it will To move the object to the old generation, you can set the GC age threshold through the parameter -XX:MaxTenuringThreshold.

Old Generation

The space size of the old generation is the difference between the two parameters -Xmx and -Xmn, which is used to store objects that are still alive after several Minor GCs. . When there is insufficient space in the old generation, Major GC/Full GC will be triggered, which is generally more than 10 times slower than Minor GC.

Permanent generation

In the HotSpot implementation before JDK8, the metadata of the class such as method data, method information (bytecode, stack and variable size), runtime The constant pool, determined symbol references and virtual method tables are saved in the permanent generation. The default size of the permanent generation is 64M for 32-bit and 85M for 64-bit. It can be set through the parameter -XX:MaxPermSize. Once the class is If the metadata exceeds the permanent generation size, an OOM exception will be thrown.

The virtual machine team removed the permanent generation from the Java heap in HotSpot of JDK8, and saved the metadata of the class directly in the local memory area (off-heap memory), which is called metaspace.

What are the benefits of doing this?

Experienced students will find that the tuning process of the permanent generation is very difficult. The size of the permanent generation is difficult to determine because it involves too many factors, such as the total number of classes, the size of the constant pool, the number of methods, etc. , and the data in the permanent generation may move with each Full GC.

In JDK8, the metadata of the class is stored in local memory. The maximum allocable space of the metaspace is the system’s available memory space, which can avoid the memory overflow problem of the permanent generation, but the memory consumption needs to be monitored. , once a memory leak occurs, it will occupy a large amount of local memory.

ps: In HotSpot before JDK7, strings in the string constant pool were stored in the permanent generation, which may cause a series of performance problems and memory overflow errors. In JDK8, only string references are stored in the string constant pool.

How to determine whether an object is alive

Before the GC action occurs, it is necessary to determine which objects in the heap memory are alive. There are generally two methods: reference counting and accessible. Expressive analysis method.

1. Reference counting method

Add a reference counter to the object. Whenever an object references it, the counter increases by 1. When the object is used up, , the counter is decremented by 1, and an object with a counter value of 0 indicates that it cannot be used anymore.

The reference counting method is simple to implement and efficient in determination, but it cannot solve the problem of mutual references between objects.

public class GCtest {
    private Object instance = null;
    private static final int _10M = 10 * 1 << 20;
    // 一个对象占10M,方便在GC日志中看出是否被回收
    private byte[] bigSize = new byte[_10M];
    public static void main(String[] args) {
        GCtest objA = new GCtest();
        GCtest objB = new GCtest();
        objA.instance = objB;
        objB.instance = objA;
        objA = null;
        objB = null;
        System.gc();
    }
}
Copy after login

By adding the -XX:+PrintGC parameter, the running result is:

[GC (System.gc()) [PSYoungGen: 26982K->1194K(75776K)] 26982K->1202K(249344K), 0.0010103 secs]
Copy after login


从GC日志中可以看出objA和objB虽然相互引用,但是它们所占的内存还是被垃圾收集器回收了。

2、可达性分析法

通过一系列称为 “GC Roots” 的对象作为起点,从这些节点开始向下搜索,搜索路径称为 “引用链”,以下对象可作为GC Roots:

本地变量表中引用的对象

方法区中静态变量引用的对象

方法区中常量引用的对象

Native方法引用的对象

当一个对象到 GC Roots 没有任何引用链时,意味着该对象可以被回收。

Things about Java GC (1)

在可达性分析法中,判定一个对象objA是否可回收,至少要经历两次标记过程:

1、如果对象objA到 GC Roots没有引用链,则进行第一次标记。

2、如果对象objA重写了finalize()方法,且还未执行过,那么objA会被插入到F-Queue队列中,由一个虚拟机自动创建的、低优先级的Finalizer线程触发其finalize()方法。finalize()方法是对象逃脱死亡的最后机会,GC会对队列中的对象进行第二次标记,如果objA在finalize()方法中与引用链上的任何一个对象建立联系,那么在第二次标记时,objA会被移出“即将回收”集合。

看看具体实现

public class FinalizerTest {
    public static FinalizerTest object;
    public void isAlive() {
        System.out.println("I&#39;m alive");
    }
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        System.out.println("method finalize is running");
        object = this;
    }
    public static void main(String[] args) throws Exception {
        object = new FinalizerTest();
        // 第一次执行,finalize方法会自救
        object = null;
        System.gc();
        Thread.sleep(500);
        if (object != null) {
            object.isAlive();
        } else {
            System.out.println("I&#39;m dead");
        }
        // 第二次执行,finalize方法已经执行过
        object = null;
        System.gc();
        Thread.sleep(500);
        if (object != null) {
            object.isAlive();
        } else {
            System.out.println("I&#39;m dead");
        }
    }
}
Copy after login

执行结果:

method finalize is running
I&#39;m alive
I&#39;m dead
Copy after login

从执行结果可以看出:

第一次发生GC时,finalize方法的确执行了,并且在被回收之前成功逃脱;

第二次发生GC时,由于finalize方法只会被JVM调用一次,object被回收。

当然了,在实际项目中应该尽量避免使用finalize方法。

Java GC 的那些事(1)

Java GC的那些事(2)

以上就是Java GC 的那些事(1)的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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
3 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
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles