本文介绍了Java 在对象释放和垃圾回收后仍然使用系统内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行 JVM 1.5.0(Mac OS X 默认),并且我正在活动监视器中监视我的 Java 程序.我有以下几点:

I am running JVM 1.5.0 (Mac OS X Default), and I am monitoring my Java program in the Activity Monitor. I have the following:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;

public class MemoryTest {

public static void memoryUsage() {
 System.out.println(
     Runtime.getRuntime().totalMemory() - 
     Runtime.getRuntime().freeMemory()
 );
}

public static void main( String[] args ) throws IOException {

    /* create a list */
    ArrayList<Date> list = new ArrayList<Date>();

    /* fill it with lots of data */
    for ( int i = 0; i < 5000000; i++ ) {
        list.add( new Date() );
    } // systems shows ~164 MB of physical being used

    /* clear it */
    memoryUsage();      //  about 154 MB
    list.clear();
    list = null;
    System.gc();
    memoryUsage();      //  about 151 KB, garbage collector worked

    // system still shows 164 MB of physical being used.
    System.out.println("Press enter to end...");
    BufferedReader br = new BufferedReader( 
            new InputStreamReader( System.in )
            );
    br.readLine();
}

}

那么为什么即使垃圾收集器似乎工作得很好,物理内存也没有被释放?

So why doesn't the physical memory get freed even though the garbage collector seems to work just fine?

推荐答案

许多 JVM 从不将内存返回给操作系统.它是否这样做是特定于实现的.对于那些没有的,在启动时指定的内存限制,通常通过 -Xmx 标志,是为其他应用程序保留内存的主要方法.

Many JVMs never return memory to the operating system. Whether it does so or not is implementation-specific. For those that don't, the memory limits specified at startup, usually through the -Xmx flag, are the primary means to reserve memory for other applications.

我很难找到关于这个主题的文档,但是 Sun 的 Java 5 的垃圾收集器文档 确实解决了这个问题,表明在正确的条件下,如果使用正确的收集器,堆将缩小——默认情况下,如果堆的 70% 以上空闲,它将缩小所以只有 40% 是免费的.控制这些的命令行选项是 -XX:MinHeapFreeRatio-XX:MaxHeapFreeRatio.

I am having a hard time finding documentation on this subject, but the garbage collector documentation for Sun's Java 5 does address this, suggesting that under the right conditions, the heap will shrink if the correct collector is used—by default, if more that 70% of the heap is free, it will shrink so that only 40% is free. The command line options to control these are -XX:MinHeapFreeRatio and -XX:MaxHeapFreeRatio.

这篇关于Java 在对象释放和垃圾回收后仍然使用系统内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 07:01