gpt4 book ai didi

java - sun.nio.ch.FileChannelImpl 中的 System.gc() 调用是坏情况吗?

转载 作者:行者123 更新时间:2023-12-05 01:26:04 26 4
gpt4 key购买 nike

try {
// If no exception was thrown from map0, the address is valid
addr = map0(imode, mapPosition, mapSize);
} catch (OutOfMemoryError x) {
// An OutOfMemoryError may indicate that we've exhausted memory
// so force gc and re-attempt map
System.gc();
try {
Thread.sleep(100);
} catch (InterruptedException y) {
Thread.currentThread().interrupt();
}
try {
addr = map0(imode, mapPosition, mapSize);
} catch (OutOfMemoryError y) {
// After a second OOME, fail
throw new IOException("Map failed", y);
}
}

来自 jdk/FileChannelImpl.java at jdk8-b120 .

这对异常恢复有帮助吗?

最佳答案

当对象分配失败并返回 OutOfMemoryError 时,垃圾收集器确实已经尽力回收未使用对象的内存或扩展堆。所以打电话System.gc()抓到之后OutOfMemoryError将毫无意义。

一种特殊情况是垃圾收集器重复回收少量内存的情况,因此应用程序可以继续,但必须在下一次分配时立即执行另一次垃圾收集。一些垃圾收集器抛出 OutOfMemoryError当他们检测到应用程序将超过 98% 的 CPU 时间用于垃圾收集时,会显示消息“GC Overhead Limit Exceeded”。在这种情况下,调用 System.gc()会适得其反,因为那样的话,应用程序会花费更多时间在垃圾收集以及创建和处理上 OutOfMemoryError


FileChannelImpl的情况不同。 map0可能由于 native 内存不足或在 32 位系统的情况下地址空间不足而失败。在这些情况下,堆内存管理器不会生成 OutOfMemoryError。并且垃圾收集器可能没有运行。但是要回收 native 内存或地址空间,关联的 ByteBuffer实例必须得到垃圾收集,这样他们的清洁工才能运行。这是一个罕见的极端情况,调用 System.gc();有道理。

它仍然很脆弱,因为System.gc();不能保证收集所有对象或根本运行垃圾收集器。 JEP 383应该通过更好地控制 native 分配的生命周期来解决这个问题。

关于java - sun.nio.ch.FileChannelImpl 中的 System.gc() 调用是坏情况吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70458298/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com