Java:OutOfMemoryError异常和freeMemory() [英] Java: OutOfMemoryError Exception and freeMemory()

查看:104
本文介绍了Java:OutOfMemoryError异常和freeMemory()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下测试程序:

public static void main(String[] args)
{       
    HashMap<Integer, String> hm = new HashMap<Integer,String>(); 
    int i = 1;  
    while(true)
    {
        hm.put(i, "blah");
        i++;
        System.out.println("############"); 
        System.out.println("Max mem: " + Runtime.getRuntime().maxMemory()); 
        System.out.println("Total mem: " + Runtime.getRuntime().totalMemory()); 
        System.out.println("Free mem:" + Runtime.getRuntime().freeMemory());
    }
}

如果运行此程序,则会得到以下输出:

If I run this program, I get the follwing output:

...

    ############
    Max mem: 8060928

    Total mem: 8060928

    Free mem:334400

    Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        at java.util.HashMap.addEntry(Unknown Source)
        at java.util.HashMap.put(Unknown Source)
        at Test.main(Test.java:14)

为什么我收到"OutOfMemoryError"异常,尽管方法freeMemory()返回的是还有更多的可用内存???是否有办法使用所有的freeMemory()?

Why I get an "OutOfMemoryError" Exception although the method freeMemory() returns that there is more free memory??? If there a way to use all the freeMemory()?

推荐答案

HashMap类有时会随着条目数量的增加而调整大小.即使您显示有300 + K的剩余空间,也可能不足以处理哈希存储桶的大小调整.

The HashMap class resizes on occasion as the number of entries in it grows. Even though you are showing 300+K left free, that may not be enough to handle the resizing of the hash buckets.

void resize(int newCapacity) {
    Entry[] oldTable = table;
    int oldCapacity = oldTable.length;
    if (oldCapacity == MAXIMUM_CAPACITY) {
        threshold = Integer.MAX_VALUE;
        return;
    }
    // ***possible big allocation here***
    Entry[] newTable = new Entry[newCapacity];
    transfer(newTable);
    table = newTable;
    threshold = (int)(newCapacity * loadFactor);
}

从更一般的意义上讲,在Java中不建议对堆内存(以及整个进程大小)进行细粒度的期望.后台回收以及堆中尚未回收的对象占用了您可能无法预期的空间.另外,垃圾收集器在接近满堆时逐渐使用越来越多的CPU.您想以超出预期最大分配大小的大量内存开销运行.

In a more general sense, fine grained expectations over the heap memory (and overall process size) is not recommended in Java. There are background allocations as well as objects in the heap that have yet to be reclaimed that take up space that you may not have anticipated. In addition, the garbage collector uses progressively more and more CPU as it approaches a full heap. You want to run with plenty of memory overhead above your expected maximum allocation size.

这篇关于Java:OutOfMemoryError异常和freeMemory()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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