feat(thread): 新增线程工具集与线程池构建体系

- ThreadPoolBuilder: DSL 风格线程池构建器,含 fixed/single/cached/io/cpu/scheduled 预设
- GlobalThreadPool: 全局 IO/CPU/定时三类共享线程池及便捷提交函数
- ThreadPoolMonitor: 线程池运行快照与周期监控
- ThreadPoolExt: ExecutorService/Future/CompletableFuture 便捷扩展
- AsyncTasks: 并行执行、竞速执行、重试与定时任务编排
- ThreadLocalDelegates: ThreadLocal 属性委托
- ThreadExt: Thread/Runnable 扩展与守护线程便捷创建
- ThreadUtils 增强: 休眠、线程枚举、全线程栈转储
- ThreadEvent 增强: operator invoke、属性委托、isSet 与超时取数
- 移除 pool 包旧 ThreadPool.kt
- 新增 5 个测试类共 83 个单元测试
This commit is contained in:
2026-10-19 21:09:57 +08:00
parent 6624c00553
commit 474071e43b
15 changed files with 2341 additions and 300 deletions
@@ -1,298 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ThreadPool.kt
* LastUpdate 2026-10-12 13:57:11
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.pool
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong
/**
* 可复用线程池。
*
* 与直接管理 [Thread] 的对象池不同,本实现的池对象是一个 [Worker]:
* 每个 Worker 内部持有一个**长期存活**的守护线程和一个任务队列,
* 线程通过 `while` 循环不断消费队列中的任务,从而实现真正意义上的线程复用
* (避免频繁创建/销毁线程带来的开销,并保留线程本地状态)。
*
* ## 使用方式
*
* ```kotlin
* ThreadPool(maxSize = 4, initialSize = 2).use { pool ->
* // 同步执行:借出 Worker -> 执行 -> 归还
* pool.execute { println("task on ${Thread.currentThread().name}") }
*
* // 带返回值
* val result = pool.call(Callable { 1 + 1 })
*
* // 异步提交:任务完成后自动归还 Worker
* val future = pool.submit(Callable { doSomething() })
* future.get()
*
* // 直接借出 Worker 使用
* pool.use { data -> data.obj.execute { /* ... */ } }
* }
* ```
*
* @property maxSize 最大 Worker 数量(同时也是最大并发任务数)
* @property minSize 保留的最小空闲 Worker 数量
* @property initialSize 预热的 Worker 数量
* @property namePrefix Worker 线程名前缀,最终名称为 `${namePrefix}-${id}`
* @property daemon Worker 线程是否为守护线程,默认 true
* @property uncaughtHandler 任务抛出未捕获异常时的处理器
*/
class ThreadPool(
maxSize: Int = Runtime.getRuntime().availableProcessors().coerceAtLeast(2),
minSize: Int = 0,
initialSize: Int = 1,
private val namePrefix: String = "MingLiThreadPool",
private val daemon: Boolean = true,
private val uncaughtHandler: Thread.UncaughtExceptionHandler = Thread.UncaughtExceptionHandler { _, _ -> },
) : ObjectPool<ThreadPool.Worker>(maxSize, minSize, initialSize), AutoCloseable {
/** 已提交任务总数 */
private val submittedTasks = AtomicLong(0)
/** 已完成任务总数 */
private val completedTasks = AtomicLong(0)
/** 已失败任务总数 */
private val failedTasks = AtomicLong(0)
/** 已创建的全部 Worker 引用,用于 [closeAndAwait] 等待线程退出 */
private val allWorkers = CopyOnWriteArrayList<Worker>()
override fun init(id: Int): ObjectPoolData<Worker> {
val worker = Worker(id, namePrefix, daemon, uncaughtHandler)
worker.start()
allWorkers.add(worker)
return ObjectPoolData(
obj = worker,
objectPool = this,
id = id,
name = worker.threadName,
)
}
override fun destroy(data: ObjectPoolData<Worker>) {
data.obj.shutdown()
allWorkers.remove(data.obj)
}
/**
* 同步执行任务:从池借出一个 Worker,在其线程上运行 [task],结束后归还。
* 任务的异常会被封装为 [ExecutionException] 抛出。
*/
@JvmOverloads
fun execute(task: Runnable, timeoutMillis: Long = 0) {
call(Callable { task.run(); null }, timeoutMillis)
}
/**
* 同步执行带返回值的任务。
*/
@JvmOverloads
fun <R> call(task: Callable<R>, timeoutMillis: Long = 0): R {
return useResult(timeoutMillis) { data ->
data.obj.call(task)
}
}
/**
* 异步提交任务,立即返回 [CompletableFuture]。
*
* Worker 会一直被占用直到任务执行完成,然后自动归还给池;
* 因此在 `maxSize` 达到上限时,新的提交会阻塞在 borrow 阶段。
*/
@JvmOverloads
fun <R> submit(task: Callable<R>, timeoutMillis: Long = 0): CompletableFuture<R> {
val data = borrow(timeoutMillis)
submittedTasks.incrementAndGet()
val future = data.obj.submitAsync(task)
return future.whenComplete { _, err ->
if (err != null) failedTasks.incrementAndGet() else completedTasks.incrementAndGet()
runCatching { returnObject(data) }
}
}
/** 异步提交无返回值任务;使用独立方法名避免与 [submit] 的 lambda 重载歧义 */
@JvmOverloads
fun submitRunnable(task: Runnable, timeoutMillis: Long = 0): CompletableFuture<Void?> {
return submit(Callable { task.run(); null as Void? }, timeoutMillis)
}
/** 已提交任务总数 */
fun submittedCount(): Long = submittedTasks.get()
/** 已完成任务总数 */
fun completedCount(): Long = completedTasks.get()
/** 已失败任务总数 */
fun failedCount(): Long = failedTasks.get()
/**
* 池中的工作单元:一个长期存活的守护线程 + 一个任务队列。
*
* 通过 [submit]/[call]/[execute] 向 Worker 投递任务,Worker 线程循环消费执行。
* 只有在池 [close] 时才会调用 [shutdown] 结束该线程。
*/
class Worker internal constructor(
val id: Int,
namePrefix: String,
daemon: Boolean,
private val uncaughtHandler: Thread.UncaughtExceptionHandler,
) {
private val taskQueue = LinkedBlockingQueue<Runnable>()
private val shutdown = AtomicBoolean(false)
private val started = AtomicBoolean(false)
/** Worker 线程名称 */
val threadName: String = "$namePrefix-$id"
/** Worker 线程引用,只读 */
val thread: Thread = Thread({ runLoop() }, threadName).apply {
isDaemon = daemon
}
internal fun start() {
if (started.compareAndSet(false, true)) {
thread.start()
}
}
private fun runLoop() {
while (!shutdown.get() || taskQueue.isNotEmpty()) {
val task = try {
// 使用轮询而非 take(),以便 shutdown 标志能及时生效
taskQueue.poll(100, TimeUnit.MILLISECONDS)
} catch (_: InterruptedException) {
if (shutdown.get()) break else null
}
if (task != null) {
try {
task.run()
} catch (t: Throwable) {
try {
uncaughtHandler.uncaughtException(thread, t)
} catch (_: Throwable) {
// 忽略处理器自身的异常,防止线程意外退出
}
}
}
}
}
/**
* 异步提交任务,返回 Future。任务在该 Worker 线程上执行。
* @throws IllegalStateException 若 Worker 已关闭
*/
fun <R> submitAsync(task: Callable<R>): CompletableFuture<R> {
check(!shutdown.get()) { "Worker[$threadName] already shutdown" }
val future = CompletableFuture<R>()
val wrapper = Runnable {
try {
future.complete(task.call())
} catch (t: Throwable) {
future.completeExceptionally(t)
}
}
if (!taskQueue.offer(wrapper)) {
future.completeExceptionally(IllegalStateException("Worker[$threadName] rejected task"))
}
return future
}
/** 同步执行任务,返回结果 */
fun <R> call(task: Callable<R>): R {
try {
return submitAsync(task).get()
} catch (e: ExecutionException) {
throw e.cause ?: e
}
}
/** 同步执行任务,忽略返回值 */
fun execute(task: Runnable) {
call(Callable { task.run(); null })
}
/** 当前待执行任务数 */
fun pendingTasks(): Int = taskQueue.size
/** Worker 是否已关闭 */
fun isShutdown(): Boolean = shutdown.get()
/** 线程是否存活 */
fun isAlive(): Boolean = thread.isAlive
internal fun shutdown() {
if (shutdown.compareAndSet(false, true)) {
thread.interrupt()
}
}
/** 等待 Worker 线程结束,最多 [timeoutMillis] 毫秒 */
@JvmOverloads
fun awaitTermination(timeoutMillis: Long = 0) {
if (timeoutMillis <= 0) thread.join() else thread.join(timeoutMillis)
}
override fun toString(): String =
"Worker(id=$id, name=$threadName, pending=${taskQueue.size}, alive=${thread.isAlive})"
}
/**
* 关闭池:销毁所有 Worker 线程。
* 由于 Worker 线程默认为守护线程,未调用 [closeAndAwait] 时不会阻塞 JVM 退出。
*/
override fun close() {
super.close()
}
/**
* 关闭池并阻塞等待所有 Worker 线程结束。
* @param timeoutMillis 每个 Worker 最长等待时间
*/
@JvmOverloads
fun closeAndAwait(timeoutMillis: Long = 5_000) {
val snapshot = allWorkers.toList()
super.close()
snapshot.forEach { it.awaitTermination(timeoutMillis) }
}
companion object {
/** 依据 CPU 核数创建默认大小的线程池 */
@JvmStatic
fun defaultPool(): ThreadPool = ThreadPool()
/** 创建固定大小的线程池 */
@JvmStatic
fun fixed(size: Int, namePrefix: String = "MingLiFixedPool"): ThreadPool =
ThreadPool(maxSize = size, minSize = size, initialSize = size, namePrefix = namePrefix)
/** 创建单线程池,保证任务串行执行 */
@JvmStatic
fun single(namePrefix: String = "MingLiSinglePool"): ThreadPool =
ThreadPool(maxSize = 1, minSize = 1, initialSize = 1, namePrefix = namePrefix)
}
}
@@ -0,0 +1,188 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile AsyncTasks.kt
* LastUpdate 2026-10-19 20:51:35
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.thread
import java.util.concurrent.Callable
import java.util.concurrent.ExecutorService
import java.util.concurrent.Future
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
// ---- 并行执行 ----
/**
* 并行执行全部任务,阻塞等待所有完成,按输入顺序返回结果。
* 任一任务失败立即抛出异常。
*
* ```kotlin
* val results = runParallel(
* { fetchUser() },
* { fetchOrder() },
* { fetchCart() },
* )
* ```
*/
fun <T> runParallel(
vararg tasks: () -> T,
executor: ExecutorService = GlobalThreadPool.io,
): List<T> = executor.invokeAllAndGet(tasks.map { Callable(it) })
/**
* 并行执行全部任务,阻塞等待所有完成,按输入顺序返回结果
*/
fun <T> runParallel(
tasks: Collection<() -> T>,
executor: ExecutorService = GlobalThreadPool.io,
): List<T> = executor.invokeAllAndGet(tasks.map { Callable(it) })
/**
* 并行执行全部任务,任一任务在超时时间内未完成则抛出 [java.util.concurrent.TimeoutException]
*/
fun <T> runParallelWithin(
timeout: Long,
unit: TimeUnit = TimeUnit.MILLISECONDS,
executor: ExecutorService = GlobalThreadPool.io,
tasks: Collection<() -> T>,
): List<T> {
val futures = tasks.map { executor.submit(Callable(it)) }
val deadline = System.nanoTime() + unit.toNanos(timeout)
return futures.map { future ->
val remaining = deadline - System.nanoTime()
if (remaining <= 0) throw java.util.concurrent.TimeoutException("runParallel timeout $timeout $unit")
future.get(remaining, TimeUnit.NANOSECONDS)
}
}
/**
* 执行全部任务,返回第一个成功完成的任务结果,其余任务取消。
*/
fun <T> firstCompleted(
vararg tasks: () -> T,
executor: ExecutorService = GlobalThreadPool.io,
): T = executor.invokeAny(tasks.map { Callable(it) })
/**
* 执行全部任务,返回第一个成功完成的任务结果,其余任务取消
*/
fun <T> firstCompleted(
tasks: Collection<() -> T>,
executor: ExecutorService = GlobalThreadPool.io,
): T = executor.invokeAny(tasks.map { Callable(it) })
// ---- 集合工具 ----
/**
* 等待所有 Future 完成并按顺序收集结果,任一失败抛出原始异常
*/
fun <T> awaitAll(futures: Collection<Future<T>>): List<T> = futures.map { it.await() }
/**
* 提交全部 Callable 并阻塞等待所有完成,任一失败抛出原始异常
*/
fun <T> ExecutorService.invokeAllAndGet(tasks: Collection<Callable<T>>): List<T> =
invokeAll(tasks).map { it.await() }
/**
* 等待所有 Future 完成,失败的任务返回 null(不中断整体流程)
*/
fun <T> awaitAllOrNull(futures: Collection<Future<T>>): List<T?> =
futures.map { it.getOrNull() }
// ---- 重试 ----
/**
* 带重试的调用:任务抛出异常时重试,全部失败抛出最后一次异常。
*
* ```kotlin
* val data = callWithRetry(3, delayMillis = 500) { httpGet(url) }
* ```
*
* @param times 总尝试次数(含首次),必须 >= 1
* @param delayMillis 每次重试前的等待毫秒数
*/
fun <T> callWithRetry(
times: Int,
delayMillis: Long = 0,
task: () -> T,
): T {
require(times >= 1) { "times must be >= 1: $times" }
var last: Throwable? = null
repeat(times) { attempt ->
try {
return task()
} catch (t: Throwable) {
last = t
// 最后一次失败不再等待
if (attempt < times - 1 && delayMillis > 0) {
Thread.sleep(delayMillis)
}
}
}
throw last ?: IllegalStateException("unreachable")
}
/**
* 在全局 IO 池中带重试执行任务
*/
fun <T> callAsyncWithRetry(
times: Int,
delayMillis: Long = 0,
task: () -> T,
): Future<T> = GlobalThreadPool.io.submit(Callable { callWithRetry(times, delayMillis, task) })
// ---- 定时任务 ----
/**
* 延迟执行任务(全局定时池)
*
* ```kotlin
* delayRun(5, TimeUnit.SECONDS) { log.info("5s later") }
* ```
*/
fun delayRun(
delay: Long,
unit: TimeUnit = TimeUnit.MILLISECONDS,
action: () -> Unit,
): ScheduledFuture<*> = GlobalThreadPool.scheduled.schedule(action, delay, unit)
/**
* 以固定频率执行任务(周期 = 任务耗时 + [period]),全局定时池
*/
fun scheduleWithFixedDelay(
period: Long,
unit: TimeUnit = TimeUnit.MILLISECONDS,
initialDelay: Long = 0,
action: () -> Unit,
): ScheduledFuture<*> =
GlobalThreadPool.scheduled.scheduleWithFixedDelay(action, initialDelay, period, unit)
/**
* 以固定频率执行任务(周期恒定为 [period]),全局定时池
*/
fun scheduleAtFixedRate(
period: Long,
unit: TimeUnit = TimeUnit.MILLISECONDS,
initialDelay: Long = 0,
action: () -> Unit,
): ScheduledFuture<*> =
GlobalThreadPool.scheduled.scheduleAtFixedRate(action, initialDelay, period, unit)
@@ -0,0 +1,122 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile GlobalThreadPool.kt
* LastUpdate 2026-10-19 20:51:35
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.thread
import com.mingliqiye.utils.netty.NamedThreadFactory
import com.mingliqiye.utils.system.availableProcessors
import java.util.concurrent.Callable
import java.util.concurrent.Future
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.ThreadPoolExecutor
/**
* 全局线程池,按任务类型提供三类共享池,通过 `by lazy` 懒加载。
*
* ```kotlin
* GlobalThreadPool.io.execute { download() }
* val result = GlobalThreadPool.cpu.submit { compute() }.get()
* runAsync { log("done") }
* ```
*/
object GlobalThreadPool {
/** IO 密集型全局池:线程多、队列有界,适合网络/磁盘等阻塞任务 */
val io: ThreadPoolExecutor by lazy {
threadPool("MingLiGlobalIO") {
corePoolSize = availableProcessors * 2
maximumPoolSize = availableProcessors * 4
boundedQueue(1024)
allowCoreThreadTimeout = true
daemon = true
}
}
/** CPU 密集型全局池:线程数等于核数,适合纯计算任务 */
val cpu: ThreadPoolExecutor by lazy {
threadPool("MingLiGlobalCPU") {
corePoolSize = availableProcessors
maximumPoolSize = availableProcessors
daemon = true
}
}
/** 全局定时任务池 */
val scheduled: ScheduledThreadPoolExecutor by lazy {
// 包装一层将定时线程设为守护线程,避免阻塞 JVM 退出
val base = NamedThreadFactory.of("MingLiGlobalScheduled")
ScheduledThreadPoolExecutor(
(availableProcessors / 2).coerceAtLeast(1),
) { runnable -> base.newThread(runnable).apply { isDaemon = true } }
}
// ---- 便捷提交 ----
@JvmStatic
fun execute(runnable: Runnable): Future<*> = io.submit(runnable)
@JvmStatic
fun <T> submit(callable: Callable<T>): Future<T> = io.submit(callable)
@JvmStatic
fun submit(runnable: Runnable): Future<*> = io.submit(runnable)
@JvmStatic
fun <T> submit(runnable: Runnable, result: T): Future<T> = io.submit(runnable, result)
/**
* 优雅关闭全部线程池(先正常关闭,超时后强制关闭)
*/
@JvmStatic
fun shutdownAll() {
io.shutdownGracefully()
cpu.shutdownGracefully()
scheduled.shutdownGracefully()
}
}
/**
* 向全局 IO 池提交无返回值任务
*/
fun runAsync(block: () -> Unit): Future<*> = GlobalThreadPool.io.submit(block)
/**
* 向全局 IO 池提交带返回值任务
*/
fun <T> callAsync(block: () -> T): Future<T> = GlobalThreadPool.io.submit(Callable(block))
/**
* 向全局 CPU 池提交计算任务
*/
fun <T> computeAsync(block: () -> T): Future<T> = GlobalThreadPool.cpu.submit(Callable(block))
/**
* 在全局 IO 池执行任务并阻塞等待完成
*/
fun runAsyncAwait(block: () -> Unit) {
GlobalThreadPool.io.submit(block).get()
}
/**
* 在全局 IO 池执行任务并阻塞等待结果
*/
fun <T> callAsyncAwait(block: () -> T): T = GlobalThreadPool.io.submit(Callable(block)).get()
@@ -24,11 +24,17 @@ package com.mingliqiye.utils.thread
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* 线程事件同步工具类,用于线程间的事件通知和等待
* 线程事件同步工具类,用于线程间的事件通知和等待。
*
* 支持 Kotlin 便捷语法:
* - `event()` 读取数据,`event(newData)` 设置数据并唤醒等待线程
* - `val value by event` 直接作为属性委托使用
*/
open class ThreadEvent<T> {
open class ThreadEvent<T> : ReadWriteProperty<Any?, T> {
private var latch = CountDownLatch(1)
@@ -94,6 +100,16 @@ open class ThreadEvent<T> {
return data
}
/**
* 等待事件被设置并获取数据,超时返回 null
*
* @param timeout 等待超时时间
* @param unit 时间单位
* @return 事件数据;超时未触发则返回 null
*/
fun awaitAndGetOrNull(timeout: Long, unit: TimeUnit): T? =
if (await(timeout, unit)) data else null
/**
* 在指定超时时间内等待事件被设置
*
@@ -105,8 +121,42 @@ open class ThreadEvent<T> {
return latch.await(timeout, unit)
}
/**
* 事件是否已被设置(自上次 [reset] 以来)
*/
fun isSet(): Boolean = latch.count == 0L
fun setAndReset(data: T) {
set(data)
reset()
}
// ---- Kotlin 便捷语法 ----
/** 读取事件数据:`val d = event()` */
operator fun invoke(): T = data
/** 设置事件数据并唤醒等待线程:`event(newData)` */
operator fun invoke(data: T) = set(data)
/** 支持属性委托:`var value by event` */
override operator fun getValue(thisRef: Any?, property: KProperty<*>): T = data
/** 支持属性委托:`value = newData` 等价于 [set] */
override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = set(value)
/**
* 以自身为委托,返回属性委托视图
*/
fun asDelegate(): ReadWriteProperty<Any?, T> = this
companion object {
/**
* 创建事件实例
*
* @param data 初始数据
*/
@JvmStatic
fun <T> of(data: T): ThreadEvent<T> = ThreadEvent(data)
}
}
@@ -0,0 +1,164 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ThreadExt.kt
* LastUpdate 2026-10-19 20:51:35
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.thread
// ---- Runnable 扩展 ----
/**
* 将 [Runnable] 包装为新线程并立即启动
*
* ```kotlin
* Runnable { download() }.startThread("downloader", daemon = true)
* ```
*
* @param name 线程名称,null 表示使用默认名称
* @param daemon 是否为守护线程
* @param uncaughtHandler 未捕获异常处理器
*/
fun Runnable.startThread(
name: String? = null,
daemon: Boolean = true,
uncaughtHandler: Thread.UncaughtExceptionHandler? = null,
): Thread = Thread(this).apply {
if (name != null) this.name = name
isDaemon = daemon
if (uncaughtHandler != null) setUncaughtExceptionHandler(uncaughtHandler)
start()
}
/**
* 将 [Runnable] 包装为新线程但不启动
*/
fun Runnable.asThread(
name: String? = null,
daemon: Boolean = true,
uncaughtHandler: Thread.UncaughtExceptionHandler? = null,
): Thread = Thread(this).apply {
if (name != null) this.name = name
isDaemon = daemon
if (uncaughtHandler != null) setUncaughtExceptionHandler(uncaughtHandler)
}
// ---- Thread 扩展 ----
/**
* 为线程设置未捕获异常处理器(链式风格)
*
* ```kotlin
* thread.onUncaught { t, e -> log.error("thread {} crashed", t.name, e) }
* ```
*/
fun Thread.onUncaught(action: (Thread, Throwable) -> Unit): Thread = apply {
setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler { t, e -> action(t, e) })
}
/**
* 安静休眠:忽略中断,但恢复线程中断状态以便上层感知
*/
fun Thread.sleepQuietly(millis: Long, nanos: Int = 0) {
try {
Thread.sleep(millis, nanos)
} catch (_: InterruptedException) {
interrupt() // 恢复中断标志
}
}
/**
* 若线程尚未启动则启动,返回自身(链式风格);已终止线程无法重启,静默忽略。
*/
fun Thread.startIfNotStarted(): Thread {
if (isAlive) return this
return try {
start()
this
} catch (_: IllegalThreadStateException) {
this
}
}
/**
* 阻塞等待线程结束并捕获中断
*
* @return 是否在中断前正常结束
*/
fun Thread.joinQuietly(millis: Long = 0): Boolean = try {
join(millis)
!isAlive
} catch (_: InterruptedException) {
false
}
/**
* 转储线程调用栈(便于排查卡死问题)
*/
fun Thread.dumpStackTrace(): String = buildString {
append("thread [").append(name).append("] state=").append(state)
stackTrace.forEach { element ->
append("\n\tat ").append(element)
}
}
// ---- 顶层便捷函数 ----
/**
* 创建并启动守护线程
*
* ```kotlin
* val t = daemonThread("watchdog") { watch() }
* ```
*/
fun daemonThread(
name: String = "MingLiDaemon",
start: Boolean = true,
uncaughtHandler: Thread.UncaughtExceptionHandler? = null,
block: () -> Unit,
): Thread = Thread(block, name).apply {
isDaemon = true
if (uncaughtHandler != null) setUncaughtExceptionHandler(uncaughtHandler)
if (start) start()
}
/**
* 创建非守护线程
*/
fun userThread(
name: String = "MingLiUser",
start: Boolean = true,
uncaughtHandler: Thread.UncaughtExceptionHandler? = null,
block: () -> Unit,
): Thread = Thread(block, name).apply {
isDaemon = false
if (uncaughtHandler != null) setUncaughtExceptionHandler(uncaughtHandler)
if (start) start()
}
/**
* 便捷构造未捕获异常处理器
*/
fun uncaughtExceptionHandler(action: (Thread, Throwable) -> Unit): Thread.UncaughtExceptionHandler =
Thread.UncaughtExceptionHandler { t, e -> action(t, e) }
/**
* 获取当前线程
*/
fun currentThread(): Thread = Thread.currentThread()
@@ -0,0 +1,75 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ThreadLocalDelegates.kt
* LastUpdate 2026-10-19 20:51:35
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.thread
import java.util.function.Supplier
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* 将 [ThreadLocal] 包装为 Kotlin 属性委托,通过 `by` 关键字即可实现线程级变量:
*
* ```kotlin
* object RequestContext {
* var userId: Long by threadLocal { 0L }
* var traceId: String? by nullableThreadLocal()
* }
* ```
*
* 每个线程读写互不影响,切换线程后自动获得新线程的隔离值。
*/
class ThreadLocalDelegate<T>(
private val threadLocal: ThreadLocal<T>,
) : ReadWriteProperty<Any?, T> {
override fun getValue(thisRef: Any?, property: KProperty<*>): T = threadLocal.get()
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
threadLocal.set(value)
}
override fun toString(): String = threadLocal.toString()
}
/**
* 创建带初始值的线程局部属性委托
*
* @param initial 每个线程首次访问时的初始化器
*/
fun <T> threadLocal(initial: () -> T): ThreadLocalDelegate<T> =
ThreadLocalDelegate(ThreadLocal.withInitial(Supplier(initial)))
/**
* 创建无初始值的线程局部属性委托,属性类型需声明为可空:
*
* ```kotlin
* var value: String? by nullableThreadLocal()
* ```
*/
fun <T : Any> nullableThreadLocal(): ThreadLocalDelegate<T?> =
ThreadLocalDelegate(ThreadLocal())
/**
* 将已有 [ThreadLocal] 实例包装为属性委托
*/
fun <T> ThreadLocal<T>.asDelegate(): ThreadLocalDelegate<T> = ThreadLocalDelegate(this)
@@ -0,0 +1,234 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ThreadPoolBuilder.kt
* LastUpdate 2026-10-19 20:51:35
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.thread
import com.mingliqiye.utils.netty.NamedThreadFactory
import com.mingliqiye.utils.system.availableProcessors
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.RejectedExecutionHandler
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.SynchronousQueue
import java.util.concurrent.ThreadFactory
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
/**
* 线程池构建器,采用链式 + DSL 风格配置 [ThreadPoolExecutor]。
*
* 充分利用 Kotlin 默认参数与具名参数,仅需覆盖关心的配置项:
*
* ```kotlin
* val pool = threadPool("biz-pool") {
* corePoolSize = 8
* maximumPoolSize = 16
* queueCapacity = 1000 // 有界队列,防止任务无限堆积
* keepAliveSeconds = 30
* allowCoreThreadTimeout = true
* daemon = true
* rejectedHandler = ThreadPoolExecutor.AbortPolicy()
* }
* ```
*/
class ThreadPoolBuilder internal constructor() {
/** 线程池名称,用于线程命名 */
var name: String = "MingLiPool"
/** 核心线程数,默认 CPU 核数 */
var corePoolSize: Int = availableProcessors
/** 最大线程数,默认 CPU 核数 x2 */
var maximumPoolSize: Int = availableProcessors * 2
/** 非核心线程空闲存活时间(秒) */
var keepAliveSeconds: Long = 60
/** 是否允许核心线程空闲超时回收 */
var allowCoreThreadTimeout: Boolean = false
/** 任务队列容量,<= 0 表示使用无界队列 */
var queueCapacity: Int = 0
/** 工作队列,设置 [queueCapacity] 后将被覆盖 */
var workQueue: BlockingQueue<Runnable> = LinkedBlockingQueue()
/** 线程是否为守护线程 */
var daemon: Boolean = false
/** 线程优先级 */
var priority: Int = Thread.NORM_PRIORITY
/** 任务拒绝策略,默认由调用线程执行 */
var rejectedHandler: RejectedExecutionHandler = ThreadPoolExecutor.CallerRunsPolicy()
/** 未捕获异常处理器 */
var uncaughtHandler: Thread.UncaughtExceptionHandler? = null
/** 自定义线程工厂,默认使用 [NamedThreadFactory] */
var threadFactory: ThreadFactory? = null
/**
* 使用无界队列(默认行为)
*/
fun unboundedQueue(): ThreadPoolBuilder = apply {
queueCapacity = 0
workQueue = LinkedBlockingQueue()
}
/**
* 使用有界队列
*
* @param capacity 队列容量,必须大于 0
*/
fun boundedQueue(capacity: Int): ThreadPoolBuilder = apply {
require(capacity > 0) { "queue capacity must be positive: $capacity" }
queueCapacity = capacity
workQueue = ArrayBlockingQueue(capacity)
}
/**
* 使用同步队列,任务直接交接给线程(适合缓存线程池场景)
*/
fun synchronousQueue(): ThreadPoolBuilder = apply {
queueCapacity = 1
workQueue = SynchronousQueue()
}
/**
* 构建线程池
*
* @return 配置完成的 [ThreadPoolExecutor]
*/
fun build(): ThreadPoolExecutor {
val baseFactory = threadFactory ?: NamedThreadFactory.of(name)
// 提取局部变量,避免 apply 块内与 Thread 自身属性混淆
val daemonThread = daemon
val threadPriority = priority
val exceptionHandler = uncaughtHandler
// 需要定制 daemon/priority/异常处理时包装一层,否则直接复用
val factory = if (daemonThread || threadPriority != Thread.NORM_PRIORITY || exceptionHandler != null) {
ThreadFactory { runnable ->
baseFactory.newThread(runnable).apply {
isDaemon = daemonThread
this.priority = threadPriority
exceptionHandler?.let { setUncaughtExceptionHandler(it) }
}
}
} else baseFactory
return ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveSeconds,
TimeUnit.SECONDS,
workQueue,
factory,
rejectedHandler,
).apply {
if (allowCoreThreadTimeout) allowCoreThreadTimeOut(true)
}
}
}
/**
* 以 DSL 方式构建线程池
*
* ```kotlin
* val pool = threadPool("order-pool") {
* corePoolSize = 4
* boundedQueue(500)
* }
* ```
*
* @param name 线程池名称
* @param configure 配置块
*/
fun threadPool(
name: String = "MingLiPool",
configure: ThreadPoolBuilder.() -> Unit = {},
): ThreadPoolExecutor = ThreadPoolBuilder().apply {
this.name = name
configure()
}.build()
/**
* 创建固定大小线程池,任务队列无界
*/
fun fixedThreadPool(size: Int, name: String = "MingLiFixedPool"): ThreadPoolExecutor =
threadPool(name) {
corePoolSize = size
maximumPoolSize = size
}
/**
* 创建单线程池,保证任务串行执行
*/
fun singleThreadPool(name: String = "MingLiSinglePool"): ThreadPoolExecutor =
threadPool(name) {
corePoolSize = 1
maximumPoolSize = 1
}
/**
* 创建缓存线程池,空闲线程 60 秒后回收
*/
fun cachedThreadPool(name: String = "MingLiCachedPool"): ThreadPoolExecutor =
threadPool(name) {
corePoolSize = 0
maximumPoolSize = Int.MAX_VALUE
keepAliveSeconds = 60
synchronousQueue()
}
/**
* 创建 IO 密集型线程池:更多线程 + 有界队列
*/
fun ioThreadPool(name: String = "MingLiIoPool"): ThreadPoolExecutor =
threadPool(name) {
corePoolSize = availableProcessors * 2
maximumPoolSize = availableProcessors * 4
boundedQueue(1024)
allowCoreThreadTimeout = true
}
/**
* 创建 CPU 密集型线程池:线程数等于核数,避免上下文切换开销
*/
fun cpuThreadPool(name: String = "MingLiCpuPool"): ThreadPoolExecutor =
threadPool(name) {
corePoolSize = availableProcessors
maximumPoolSize = availableProcessors
}
/**
* 创建定时任务线程池
*
* @param coreSize 核心线程数,默认 CPU 核数 / 2(至少 1)
* @param name 线程池名称
*/
fun scheduledThreadPool(
coreSize: Int = (availableProcessors / 2).coerceAtLeast(1),
name: String = "MingLiScheduledPool",
): ScheduledThreadPoolExecutor =
ScheduledThreadPoolExecutor(coreSize, NamedThreadFactory.of(name))
@@ -0,0 +1,150 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ThreadPoolExt.kt
* LastUpdate 2026-10-19 20:51:35
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.thread
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ExecutionException
import java.util.concurrent.Executor
import java.util.concurrent.ExecutorService
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import java.util.function.Supplier
// ---- ExecutorService 扩展 ----
/**
* 优雅关闭线程池:先正常关闭,超时未完成则强制关闭。
*
* ```kotlin
* pool.shutdownGracefully(timeout = 30, unit = TimeUnit.SECONDS)
* ```
*
* @return 线程池是否在超时前正常终止
*/
fun ExecutorService.shutdownGracefully(
timeout: Long = 30,
unit: TimeUnit = TimeUnit.SECONDS,
): Boolean {
shutdown()
if (awaitTermination(timeout, unit)) return true
shutdownNow()
return awaitTermination(timeout, unit)
}
/**
* 关闭线程池并等待终止,超时抛异常
*
* @throws IllegalStateException 线程池未能在超时时间内终止
*/
fun ExecutorService.shutdownAndAwait(
timeout: Long = 30,
unit: TimeUnit = TimeUnit.SECONDS,
) {
check(shutdownGracefully(timeout, unit)) {
"executor did not terminate within $timeout $unit"
}
}
// ---- Future 扩展 ----
/**
* 阻塞等待任务完成并返回结果;[ExecutionException] 自动解包抛出原始异常。
*/
fun <T> Future<T>.await(): T = try {
get()
} catch (e: ExecutionException) {
throw e.cause ?: e
}
/**
* 阻塞等待任务完成,返回结果;超时或执行失败返回 null。
*/
fun <T> Future<T>.getOrNull(
timeout: Long = Long.MAX_VALUE,
unit: TimeUnit = TimeUnit.MILLISECONDS,
): T? = try {
get(timeout, unit)
} catch (_: Exception) {
null
}
/**
* 阻塞等待任务完成,失败或超时返回默认值。
*/
fun <T> Future<T>.getOrDefault(
default: T,
timeout: Long = Long.MAX_VALUE,
unit: TimeUnit = TimeUnit.MILLISECONDS,
): T = getOrNull(timeout, unit) ?: default
/**
* 非阻塞取消任务
*/
fun Future<*>.cancelQuietly(): Boolean = try {
cancel(true)
} catch (_: Exception) {
false
}
/**
* 带超时等待:超时抛出 [TimeoutException],失败抛出原始异常
*/
fun <T> Future<T>.await(timeout: Long, unit: TimeUnit): T = try {
get(timeout, unit)
} catch (e: ExecutionException) {
throw e.cause ?: e
}
// ---- CompletableFuture 便捷创建 ----
/**
* 创建 [CompletableFuture] 并提交任务执行
*
* ```kotlin
* val future = completableFuture { fetchData() }
* val future2 = completableFuture(pool) { fetchData() }
* ```
*
* @param executor 执行任务的线程池,默认使用公共 ForkJoinPool
*/
fun <T> completableFuture(
executor: Executor? = null,
block: () -> T,
): CompletableFuture<T> = if (executor == null) {
CompletableFuture.supplyAsync(Supplier(block))
} else {
CompletableFuture.supplyAsync(Supplier(block), executor)
}
/**
* 在指定线程池创建无返回值 [CompletableFuture]
*/
fun runCompletableFuture(
executor: Executor? = null,
block: () -> Unit,
): CompletableFuture<Void> = if (executor == null) {
CompletableFuture.runAsync(block)
} else {
CompletableFuture.runAsync(block, executor)
}
@@ -0,0 +1,124 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ThreadPoolMonitor.kt
* LastUpdate 2026-10-19 20:51:35
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.thread
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
/**
* 线程池运行快照,一次调用获取全部关键指标。
*/
data class ThreadPoolSnapshot(
/** 当前线程数 */
val poolSize: Int,
/** 核心线程数 */
val corePoolSize: Int,
/** 最大线程数 */
val maximumPoolSize: Int,
/** 历史最大线程数 */
val largestPoolSize: Int,
/** 正在执行任务的线程数 */
val activeThreads: Int,
/** 队列中等待执行的任务数 */
val queueSize: Int,
/** 队列剩余容量(无界队列为 [Int.MAX_VALUE]) */
val queueRemainingCapacity: Int,
/** 已完成任务数 */
val completedTasks: Long,
/** 已提交任务总数 */
val totalTasks: Long,
/** 是否已调用 shutdown */
val isShutdown: Boolean,
/** 是否已终止 */
val isTerminated: Boolean,
) {
/** 线程利用率 = 活跃线程 / 最大线程,取值 [0.0, 1.0] */
val utilization: Double
get() = if (maximumPoolSize <= 0) 0.0
else activeThreads.toDouble() / maximumPoolSize
/** 队列积压率 = 队列任务 / 队列容量,无界队列返回 0.0 */
val queueLoad: Double
get() {
val capacity = queueSize + queueRemainingCapacity
return if (capacity <= 0 || capacity == Int.MAX_VALUE) 0.0
else queueSize.toDouble() / capacity
}
override fun toString(): String = buildString {
append("ThreadPoolSnapshot[")
append("size=$poolSize/$maximumPoolSize(core=$corePoolSize,largest=$largestPoolSize)")
append(",active=$activeThreads,util=${"%.1f".format(utilization * 100)}%")
append(",queue=$queueSize,load=${"%.1f".format(queueLoad * 100)}%")
append(",done=$completedTasks/$totalTasks")
append(",shutdown=$isShutdown,terminated=$isTerminated")
append("]")
}
}
/**
* 获取线程池当前运行快照
*/
fun ThreadPoolExecutor.snapshot(): ThreadPoolSnapshot = ThreadPoolSnapshot(
poolSize = poolSize,
corePoolSize = corePoolSize,
maximumPoolSize = maximumPoolSize,
largestPoolSize = largestPoolSize,
activeThreads = activeCount,
queueSize = queue.size,
queueRemainingCapacity = queue.remainingCapacity(),
completedTasks = completedTaskCount,
totalTasks = taskCount,
isShutdown = isShutdown,
isTerminated = isTerminated,
)
/**
* 周期性监控线程池,定期回调运行快照(可用于打日志、上报指标)。
*
* ```kotlin
* pool.monitor(interval = 10) { snapshot ->
* log.info("pool status: {}", snapshot)
* }
* ```
*
* @param interval 监控间隔
* @param unit 时间单位,默认秒
* @param scheduler 执行监控的定时线程池,默认 [GlobalThreadPool.scheduled]
* @param action 快照回调
* @return 可取消的定时任务句柄
*/
fun ThreadPoolExecutor.monitor(
interval: Long,
unit: TimeUnit = TimeUnit.SECONDS,
scheduler: ScheduledExecutorService = GlobalThreadPool.scheduled,
action: (ThreadPoolSnapshot) -> Unit,
): ScheduledFuture<*> =
scheduler.scheduleAtFixedRate({ action(snapshot()) }, interval, interval, unit)
/**
* 打印线程池运行报告(多行字符串)
*/
fun ThreadPoolExecutor.report(): String = snapshot().toString()
@@ -40,4 +40,98 @@ object ThreadUtils {
set(s) {
Thread.currentThread().name = s
}
/**
* 当前线程的优先级
*/
@get:JvmStatic
val currentThreadPriority: Int
get() = Thread.currentThread().priority
/**
* 当前线程是否为守护线程
*/
@JvmStatic
fun isCurrentDaemon(): Boolean = Thread.currentThread().isDaemon
/**
* 当前线程是否为主线程
*/
@JvmStatic
fun isMainThread(): Boolean = Thread.currentThread().name == "main"
/**
* 当前线程的调用栈
*/
@JvmStatic
fun currentStackTrace(): Array<StackTraceElement> = Thread.currentThread().stackTrace
/**
* 当前线程组
*/
@JvmStatic
fun currentThreadGroup(): ThreadGroup = Thread.currentThread().threadGroup
/**
* 当前线程组中活跃线程的估算数量
*/
@JvmStatic
fun activeThreadCount(): Int = Thread.activeCount()
/**
* 枚举当前线程组中所有活跃线程
*/
@JvmStatic
fun activeThreads(): Array<Thread> {
val all = arrayOfNulls<Thread>(Thread.activeCount() + 8)
val count = Thread.enumerate(all)
return all.copyOfRange(0, count).filterNotNull().toTypedArray()
}
/**
* 安静休眠:忽略中断异常,但恢复线程中断状态以便上层感知
*
* @param millis 休眠毫秒数
* @param nanos 额外纳秒数,取值 [0, 999999]
*/
@JvmStatic
@JvmOverloads
fun sleepQuietly(millis: Long, nanos: Int = 0) {
try {
Thread.sleep(millis, nanos)
} catch (_: InterruptedException) {
Thread.currentThread().interrupt()
}
}
/**
* 按时间单位休眠,忽略中断异常
*
* @param timeout 休眠时长
* @param unit 时间单位
*/
@JvmStatic
fun sleepQuietly(timeout: Long, unit: java.util.concurrent.TimeUnit) {
sleepQuietly(unit.toMillis(timeout), (unit.toNanos(timeout) % 1_000_000).toInt())
}
/**
* 转储当前线程调用栈(字符串形式)
*/
@JvmStatic
fun currentThreadDump(): String = Thread.currentThread().dumpStackTrace()
/**
* 转储所有活跃线程的调用栈,便于诊断死锁/卡死
*/
@JvmStatic
fun allThreadsDump(): String = buildString {
Thread.getAllStackTraces().forEach { (thread, stack) ->
append("thread [").append(thread.name).append("] state=").append(thread.state)
stack.forEach { element ->
append("\n\tat ").append(element)
}
append("\n\n")
}
}
}