perf(utils): 优化自动释放钩子的资源引用.

原本自动释放钩子对资源的引用, 可能会出现资源已经被关闭, 但仍然无法被 GC 回收的问题.
此次改动, 将会让钩子在关闭资源后, 将资源从列表中移除.
虽然, 自动释放钩子设计上仅会被 System.exit 动作触发, 但保险起见还是加上这个改动.
This commit is contained in:
2022-05-05 16:52:29 +08:00
parent 830f05c90a
commit 478480014a
2 changed files with 75 additions and 14 deletions

View File

@ -81,17 +81,20 @@ private object UtilsInternal {
val autoCloseableSet = mutableSetOf<AutoCloseable>()
init {
Runtime.getRuntime().addShutdownHook(Thread({
log.debug { "Closing registered hook resources..." }
autoCloseableSet.forEach {
try {
it.close()
} catch (e: Exception) {
log.error(e) { "An exception occurred while closing the resource. (Resource: `$it`)" }
}
Runtime.getRuntime().addShutdownHook(Thread(this::doCloseResources, "Shutdown-AutoCloseable"))
}
fun doCloseResources() {
log.debug { "Closing registered hook resources..." }
autoCloseableSet.removeIf {
try {
it.close()
} catch (e: Exception) {
log.error(e) { "An exception occurred while closing the resource. (Resource: `$it`)" }
}
log.debug { "All registered hook resources have been closed." }
}, "Shutdown-AutoCloseable"))
true
}
log.debug { "All registered hook resources have been closed." }
}
}