小编Dom*_*eng的帖子

尽管使用了 WeakHashMap,但 OutOfMemoryException

如果不调用System.gc(),系统将抛出 OutOfMemoryException。我不知道为什么我需要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 * 10000]);
        key = null;
        //System.gc();
    }
}
Run Code Online (Sandbox Code Playgroud)

如下,添加-XX:+PrintGCDetails打印出GC信息;如您所见,实际上,JVM 尝试执行完整的 GC 运行,但失败了;我仍然不知道原因。很奇怪,如果我取消注释该System.gc();行,结果是肯定的:

add new element 1
add new element 2
add new element 3
add new element 4 …
Run Code Online (Sandbox Code Playgroud)

java garbage-collection weak-references out-of-memory java-8

10
推荐指数
2
解决办法
321
查看次数