0
0
mirror of https://github.com/tursom/TursomServer.git synced 2025-04-05 09:00:45 +08:00

add ShutdownHook

This commit is contained in:
tursom 2021-07-04 17:23:32 +08:00
parent 59de7785ee
commit aeda793a5d
2 changed files with 40 additions and 0 deletions
ts-core
build.gradle.kts
src/main/kotlin/cn/tursom/core

View File

@ -5,6 +5,7 @@ plugins {
dependencies {
api(project(":"))
api(group = "org.slf4j", name = "slf4j-api", version = "1.7.29")
compileOnly(group = "com.google.code.gson", name = "gson", version = "2.8.6")
compileOnly(group = "io.netty", name = "netty-all", version = "4.1.43.Final")
}

View File

@ -0,0 +1,39 @@
package cn.tursom.core
import com.sun.org.slf4j.internal.LoggerFactory
import java.util.concurrent.ConcurrentLinkedDeque
import java.util.concurrent.atomic.AtomicInteger
/**
* Runtime.getRuntime().addShutdownHook() 的高效版本
* 使用线程池免去了线程创建的开销
*/
@Suppress("unused")
object ShutdownHook {
private val logger = LoggerFactory.getLogger(ShutdownHook::class.java)
private val shutdownHooks = ConcurrentLinkedDeque<() -> Unit>()
private val availableThreadCount = Runtime.getRuntime().availableProcessors() * 2
private val activeThreadCount = AtomicInteger()
fun addHook(hook: () -> Unit): Boolean {
if (activeThreadCount.incrementAndGet() <= availableThreadCount) {
addWorkThread()
}
return shutdownHooks.add(hook)
}
private fun addWorkThread() {
Runtime.getRuntime().addShutdownHook(Thread {
var hook = shutdownHooks.poll()
while (hook != null) {
try {
hook()
} catch (e: Throwable) {
//error("an exception caused on hook", e)
}
hook = shutdownHooks.poll()
}
})
}
}