为什么此示例程序中的OpenJDK 11 Java垃圾收集器“减少"了可用内存? [英] Why is OpenJDK 11 Java garbage collector *decreasing* free memory in this sample program?

查看:300
本文介绍了为什么此示例程序中的OpenJDK 11 Java垃圾收集器“减少"了可用内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用OpenJDK 11(在Windows 10上为Zulu发行版)编译并运行以下非常简单的Java程序时:

When I compile and run the following very simple Java program using OpenJDK 11 (Zulu distribution on Windows 10):

public class GCTest {
    public static void main(String[] args) {
        System.out.println("Free memory before garbage collection: " + Runtime.getRuntime().freeMemory());
        Runtime.getRuntime().gc();
        System.out.println("Free memory  after garbage collection: " + Runtime.getRuntime().freeMemory());
    }
}

看起来垃圾回收正在减少可用内存量:

it looks like garbage collection is decreasing the amount of free memory:

Free memory before garbage collection: 266881496
Free memory  after garbage collection: 7772200

当我使用Oracle的Java 8运行它时,不会发生这种情况:

This does not happen when I run it with Oracle's Java 8:

Free memory before garbage collection: 254741016
Free memory  after garbage collection: 255795064

那是为什么?

推荐答案

答案是:Java 11的GC(例如通过System.gc()显式调用时)可以减少Java进程的已用内存(在Java中称为totalMemory).

The answer is: The GC of Java 11 (when explicitly called e.g. via System.gc()) can reduce the used memory of the Java process (in Java known as totalMemory).

在Java 8中,默认垃圾收集器无法减少Java进程的已用内存. Java进程占用的内存从未被释放.仅当您切换到G1GC垃圾收集器(选项'-XX:+UseG1GC')时,Java 8才能减少Java进程的已用内存(如果您手动调用System.gc()).

In Java 8 the default garbage collector was not able to reduce the used memory of the Java process. Memory occupied by the Java process was never ever released. Only if you switch to the G1GC garbage collector (option '-XX:+UseG1GC') Java 8 is able to reduce the used memory of the Java process (if you manually call System.gc()).

空闲内存"是Java进程占用的内存,但当前未使用.因此,如果执行垃圾回收并且减少了Java占用的内存,那么可用内存的数量也会减少.

The "free memory" is the memory occupied by the Java process but that is currently not used. Therefore if you perform a garbage collection and the memory occupied by Java is reduced the amount of free memory is reduced, too.

因此,计算Java进程的可用内存"的常用方法是使用

Therefore the common way to calculate the "free memory" of a Java process is to use

Runtime r = Runtime.getRuntime();
long free = r.maxMemory() - r.totalMemory() + r.freeMemory();

这种方式与Java进程当前占用的内存无关.

This way is independent of the current memory occupied by the Java process.

这篇关于为什么此示例程序中的OpenJDK 11 Java垃圾收集器“减少"了可用内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆