mirror of
https://github.com/LamGC/ScalaBot.git
synced 2025-07-01 12:57:24 +00:00
perf(utils): 优化自动释放钩子的资源引用.
原本自动释放钩子对资源的引用, 可能会出现资源已经被关闭, 但仍然无法被 GC 回收的问题. 此次改动, 将会让钩子在关闭资源后, 将资源从列表中移除. 虽然, 自动释放钩子设计上仅会被 System.exit 动作触发, 但保险起见还是加上这个改动.
This commit is contained in:
@ -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." }
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user