mirror of
https://github.com/tursom/TursomServer.git
synced 2025-04-05 09:00:45 +08:00
add ShutdownHook
This commit is contained in:
parent
59de7785ee
commit
aeda793a5d
ts-core
@ -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")
|
||||
}
|
||||
|
39
ts-core/src/main/kotlin/cn/tursom/core/ShutdownHook.kt
Normal file
39
ts-core/src/main/kotlin/cn/tursom/core/ShutdownHook.kt
Normal 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()
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user