【问题标题】:Why JVM doesn't throw out of memory error even if the memory reached the maximum heap size?为什么即使内存达到最大堆大小,JVM 也不会抛出内存不足错误?
【发布时间】:2020-09-04 06:24:58
【问题描述】:

我正在运行 Java 编程,它在 while 循环内的内存中创建更多对象。 我将最大堆大小设置为 10MB。我正在看任务管理器,JVM 甚至在 10 MB 之后运行。 我期待内存不足。但它不是抛出,而是在while循环中不断打印一条语句。

java -Xmx10m Main

public class Main
{
    public static void main(String[] args) {
        System.out.println("Hello World");
        String s1 = "01011001100100";
        char[] charArray = s1.toCharArray();
        int index = 0;
        StringBuffer result = new StringBuffer();
        StringBuffer temp = new StringBuffer();
        
        while(index < charArray.length){
            System.out.println(index+" : "+charArray[index]);
            if(charArray[index] == '1' && charArray[index--] == '0'){ ***--- This is buggy code***
                result.append(1);
            } else {
                temp.append(charArray[index]);
            }
            index++;
        }
        System.out.println("Result >"+result);
    }
}

谢谢

【问题讨论】:

    标签: java memory-leaks out-of-memory heap-memory heap-profiling


    【解决方案1】:

    为什么即使内存达到最大堆大小,JVM也不会抛出内存不足错误?

    为什么?

    因为-xmx 参数设置了最大Java 堆大小,而不是Java 进程的总内存大小。很多 JVM 的内存利用率不在堆中。这包括:

    • 用于保存java 可执行代码和共享本机库的内存
    • 用于本机堆的内存;例如malloc 在本机代码中调用
    • 用于元空间的内存
    • 用于线程堆栈的内存
    • 文件映射到内存时使用的内存
    • 等等。

    上述某些情况可能会导致 OOME(例如,无法分配新的线程堆栈),但您使用 -xmx 设置的堆大小不会以任何方式限制它们。

    【讨论】:

    • 谢谢斯蒂芬。如何通过任何 GUI 看到堆,还有堆栈。我想直观地看到。
    • 你是什么意思“看到”?你的意思是跟踪使用了多少内存? (通常这不是一件有用的事情......)
    • 是的。我只想监控内存的使用情况,并想了解垃圾收集。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    相关资源
    最近更新 更多