【问题标题】:Java: calling to GC takes all free memoryJava:调用 GC 占用所有空闲内存
【发布时间】:2021-08-13 07:23:02
【问题描述】:

IDE:IntelliJ、JDK 16.0.2

代码:

public static void main(String[] args) {
    Runtime runtime = Runtime.getRuntime();
    System.out.println("Free memory before gc: " + runtime.freeMemory() / (1024 * 1024) + " Mb");
    runtime.gc();
    System.out.println("Free memory after gc: " + runtime.freeMemory() / (1024 * 1024) + " Mb");
}

输出:

Free memory before gc: 251 Mb
Free memory after gc: 13 Mb

问题:为什么要调用垃圾收集“吃掉”所有内存?

【问题讨论】:

  • a bit related。基本上 G1GC 将内存释放回操作系统;但这种情况很少发生。

标签: java garbage-collection


【解决方案1】:

注意freeMemory()的文档:

返回Java 虚拟机中的可用内存量

并与totalMemory()比较:

返回 Java 虚拟机中的内存总量。 此方法返回的值可能会随时间变化,具体取决于宿主环境。

所以,把你的程序改成

public static void main(String[] args) {
    Runtime runtime = Runtime.getRuntime();
    log("before gc", runtime);
    runtime.gc();
    log("after gc", runtime);
}

static void log(String point, Runtime runtime) {
    System.out.println("Free memory " + point + ": "
        + runtime.freeMemory()  / (1024 * 1024) + " MB of "
        + runtime.totalMemory() / (1024 * 1024) + " MB");
}

在我的机器上打印

Free memory before gc: 253 MB of 256 MB
Free memory after gc: 13 MB of 14 MB

表明垃圾回收不仅释放了内存,而且还给了操作系统。

默认配置旨在适应更大的应用程序,并且以如此低的内存使用率执行(完整)垃圾收集是相当不寻常的。因此,堆具有较大的初始大小并因这种强制垃圾回收而减小也就不足为奇了。

当我使用 -Xms14M 选项运行相同的程序时,我得到了

Free memory before gc: 12 MB of 14 MB
Free memory after gc: 13 MB of 14 MB

【讨论】:

  • 在 IntelliJ 中这个标志是:“-Xmx14m”
  • -Xms 设置初始堆大小,-Xmx 设置最大堆大小。对于这个小程序,两者都可以产生相同的效果。
  • 当然,当然。我的意思是关于字符串的结尾 - 最后是字母's'。在 IntelliJ 中,禁止在 VM 选项的末尾写“s”。
  • 你的意思是B
  • 是的,我的意思是 B 是奇数。干得好,你删除了它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-27
  • 2019-11-12
  • 1970-01-01
  • 2013-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多