使用 仍然会发生OOME问题

问题描述 投票:0回答:1

以下是我的测试代码;

如果不调用system.gc();,系统将引发OOME异常。我不知道为什么需要显式调用system.gc()。 JVM应该正确调用gc()本身,对吗?请指教。谢谢。

public static void main(String[] args) throws InterruptedException {
    WeakHashMap<String, int[]> hm = new WeakHashMap<>();
    int i  = 0;
    while(true) {
        Thread.sleep(1000);
        i++;
        String key = new String(new Integer(i).toString());
        System.out.println(String.format("add new element %d", i));
        hm.put(key, new int[1024 * 100000]);
        key = null;
        //System.gc();
    }
}
java out-of-memory weak-references
1个回答
0
投票

即使在WeakHashMap中,垃圾收集器也不会立即进行gc。您每次迭代都会分配大量内存(1024 * 100000 * 4个字节的内存)。我猜正在发生的是,JVM在gc发生之前就耗尽了内存。如果需要,请尝试使用-Xmx2G或更高版本运行,并测试是否可行。

© www.soinside.com 2019 - 2024. All rights reserved.