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")
}
}
}
@@ -0,0 +1,280 @@
/*
* 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.test
* CurrentFile AsyncTasksTest.kt
* LastUpdate 2026-10-19 20:58:00
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.thread
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.util.concurrent.Callable
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
import java.util.concurrent.atomic.AtomicInteger
/**
* AsyncTasks 并发任务编排与 GlobalThreadPool 的测试
*/
class AsyncTasksTest {
// ---- runParallel ----
@Test
fun testRunParallelVararg() {
val results = runParallel(
{ 1 },
{ 2 },
{ 3 },
)
assertEquals(listOf(1, 2, 3), results)
}
@Test
fun testRunParallelCollection() {
val tasks = listOf<() -> String>({ "a" }, { "b" }, { "c" })
assertEquals(listOf("a", "b", "c"), runParallel(tasks))
}
@Test
fun testRunParallelKeepsOrder() {
// 慢任务在前,结果仍按输入顺序返回
val results = runParallel(
{ Thread.sleep(100); "slow" },
{ "fast" },
)
assertEquals(listOf("slow", "fast"), results)
}
@Test
fun testRunParallelCustomExecutor() {
val pool = fixedThreadPool(2, "parallel-test")
try {
val results = runParallel({ 1 }, { 2 }, executor = pool)
assertEquals(listOf(1, 2), results)
} finally {
pool.shutdown()
}
}
@Test
fun testRunParallelFailure() {
assertThrows(RuntimeException::class.java) {
runParallel(
{ 1 },
{ throw RuntimeException("task failed") },
)
}
}
@Test
fun testRunParallelWithin() {
val tasks = listOf<() -> Int>({ 1 }, { 2 })
assertEquals(listOf(1, 2), runParallelWithin(5, TimeUnit.SECONDS, tasks = tasks))
}
@Test
fun testRunParallelWithinTimeout() {
assertThrows(TimeoutException::class.java) {
runParallelWithin(
timeout = 100,
unit = TimeUnit.MILLISECONDS,
tasks = listOf({ Thread.sleep(1000); 1 }),
)
}
}
// ---- firstCompleted ----
@Test
fun testFirstCompleted() {
val result = firstCompleted(
{ Thread.sleep(200); "slow" },
{ "fast" },
)
assertEquals("fast", result)
}
// ---- awaitAll / invokeAllAndGet ----
@Test
fun testAwaitAll() {
val pool = fixedThreadPool(2, "await-all-test")
try {
val futures = (1..3).map { i -> pool.submit(Callable { i * 10 }) }
assertEquals(listOf(10, 20, 30), awaitAll(futures))
} finally {
pool.shutdown()
}
}
@Test
fun testInvokeAllAndGet() {
val pool = fixedThreadPool(2, "invoke-all-test")
try {
val results = pool.invokeAllAndGet(listOf(Callable { "a" }, Callable { "b" }))
assertEquals(listOf("a", "b"), results)
} finally {
pool.shutdown()
}
}
@Test
fun testAwaitAllOrNull() {
val pool = fixedThreadPool(2, "await-ornull-test")
try {
val futures: List<java.util.concurrent.Future<Int>> = listOf(
pool.submit(Callable { 1 }),
pool.submit(Callable<Int> { throw RuntimeException("fail") }),
)
val results = awaitAllOrNull(futures)
assertEquals(1, results[0])
assertNull(results[1], "失败任务应返回 null")
} finally {
pool.shutdown()
}
}
// ---- callWithRetry ----
@Test
fun testCallWithRetrySuccess() {
val attempts = AtomicInteger()
val result = callWithRetry(3) {
if (attempts.incrementAndGet() < 3) throw IllegalStateException("fail")
"ok"
}
assertEquals(3, attempts.get())
assertEquals("ok", result)
}
@Test
fun testCallWithRetryExhausted() {
val attempts = AtomicInteger()
assertThrows(IllegalStateException::class.java) {
callWithRetry(2) {
attempts.incrementAndGet()
throw IllegalStateException("always fail")
}
}
assertEquals(2, attempts.get(), "应恰好尝试 2 次")
}
@Test
fun testCallAsyncWithRetry() {
val attempts = AtomicInteger()
val result = callAsyncWithRetry(3) {
if (attempts.incrementAndGet() < 3) throw IllegalStateException("fail")
"async-ok"
}.get(5, TimeUnit.SECONDS)
assertEquals(3, attempts.get())
assertEquals("async-ok", result)
}
// ---- 定时任务 ----
@Test
fun testDelayRun() {
val latch = CountDownLatch(1)
val start = System.nanoTime()
val future = delayRun(100) { latch.countDown() }
assertTrue(latch.await(3, TimeUnit.SECONDS))
assertTrue(System.nanoTime() - start >= 90_000_000L, "应至少延迟 100ms 执行")
future.cancelQuietly()
}
@Test
fun testScheduleWithFixedDelay() {
val counter = AtomicInteger()
val latch = CountDownLatch(3)
val future = scheduleWithFixedDelay(30, TimeUnit.MILLISECONDS, initialDelay = 0) {
counter.incrementAndGet()
latch.countDown()
}
try {
assertTrue(latch.await(5, TimeUnit.SECONDS))
assertTrue(counter.get() >= 3)
} finally {
future.cancel(true)
}
}
@Test
fun testScheduleAtFixedRate() {
val counter = AtomicInteger()
val latch = CountDownLatch(3)
val future = scheduleAtFixedRate(30, TimeUnit.MILLISECONDS, initialDelay = 0) {
counter.incrementAndGet()
latch.countDown()
}
try {
assertTrue(latch.await(5, TimeUnit.SECONDS))
assertTrue(counter.get() >= 3)
} finally {
future.cancel(true)
}
}
// ---- GlobalThreadPool ----
@Test
fun testGlobalPools() {
assertTrue(GlobalThreadPool.io.corePoolSize > 0)
assertTrue(GlobalThreadPool.cpu.corePoolSize > 0)
assertTrue(GlobalThreadPool.scheduled.corePoolSize > 0)
}
@Test
fun testRunAsync() {
assertNull(runAsync { }.get(5, TimeUnit.SECONDS))
}
@Test
fun testCallAsync() {
assertEquals("io", callAsync { "io" }.get(5, TimeUnit.SECONDS))
}
@Test
fun testComputeAsync() {
assertEquals(4, computeAsync { 2 + 2 }.get(5, TimeUnit.SECONDS))
}
@Test
fun testRunAsyncAwait() {
val counter = AtomicInteger()
runAsyncAwait { counter.incrementAndGet() }
assertEquals(1, counter.get())
}
@Test
fun testCallAsyncAwait() {
assertEquals("await", callAsyncAwait { "await" })
}
@Test
fun testGlobalExecute() {
val latch = CountDownLatch(1)
GlobalThreadPool.execute { latch.countDown() }
assertTrue(latch.await(5, TimeUnit.SECONDS))
}
}
@@ -0,0 +1,151 @@
/*
* 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.test
* CurrentFile ThreadEventTest.kt
* LastUpdate 2026-10-19 20:58:00
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.thread
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
/**
* ThreadEvent 线程事件同步的测试
*/
class ThreadEventTest {
/** 属性委托支持:`var value by event` */
private val event = ThreadEvent.of(0)
private var value: Int by event
@Test
fun testAwaitAndSet() {
val event = ThreadEvent.of(0)
val latch = CountDownLatch(1)
val thread = daemonThread("event-await") {
event.await()
latch.countDown()
}
event.set(42)
assertTrue(latch.await(3, TimeUnit.SECONDS))
thread.joinQuietly(2000)
assertEquals(42, event.get())
}
@Test
fun testAwaitAndGet() {
val event = ThreadEvent.of(0)
val ready = CountDownLatch(1)
val result = AtomicInteger()
val thread = daemonThread("event-await-get") {
ready.countDown()
result.set(event.awaitAndGet())
}
assertTrue(ready.await(3, TimeUnit.SECONDS))
event.set(99)
thread.joinQuietly(3000)
assertEquals(99, result.get())
}
@Test
fun testAwaitTimeout() {
val event = ThreadEvent.of(0)
val start = System.nanoTime()
assertFalse(event.await(100, TimeUnit.MILLISECONDS), "无 set 时 await 应超时")
assertTrue(System.nanoTime() - start >= 90_000_000L, "应至少等待 100ms")
}
@Test
fun testAwaitAndGetTimeout() {
val event = ThreadEvent.of(10)
// 超时未触发,返回旧数据(原有语义)
assertEquals(10, event.awaitAndGet(50, TimeUnit.MILLISECONDS))
}
@Test
fun testAwaitAndGetOrNullTimeout() {
val event = ThreadEvent.of(10)
assertNull(event.awaitAndGetOrNull(50, TimeUnit.MILLISECONDS), "超时未触发应返回 null")
}
@Test
fun testAwaitAndGetOrNullTriggered() {
val event = ThreadEvent.of(0)
val thread = daemonThread("event-or-null") {
Thread.sleep(50)
event.set(5)
}
assertEquals(5, event.awaitAndGetOrNull(3, TimeUnit.SECONDS))
thread.joinQuietly(2000)
}
@Test
fun testIsSet() {
val event = ThreadEvent.of(0)
assertFalse(event.isSet())
event.set(1)
assertTrue(event.isSet())
event.reset()
assertFalse(event.isSet())
}
@Test
fun testSetAndReset() {
val event = ThreadEvent.of(0)
event.setAndReset(5)
assertEquals(5, event.get())
assertFalse(event.isSet(), "reset 后事件应处于未设置状态")
}
@Test
fun testOperatorInvoke() {
val event = ThreadEvent.of("a")
assertEquals("a", event(), "invoke() 应读取数据")
val latch = CountDownLatch(1)
val thread = daemonThread("event-invoke") {
event.await()
latch.countDown()
}
event("b")
assertTrue(latch.await(3, TimeUnit.SECONDS))
thread.joinQuietly(2000)
assertEquals("b", event())
}
@Test
fun testPropertyDelegate() {
assertEquals(0, value)
value = 7
assertEquals(7, event.get())
assertEquals(7, value)
}
@Test
fun testFactoryOf() {
val event = ThreadEvent.of("data")
assertEquals("data", event.get())
}
}
@@ -0,0 +1,213 @@
/*
* 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.test
* CurrentFile ThreadPoolBuilderTest.kt
* LastUpdate 2026-10-19 20:58:00
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.thread
import com.mingliqiye.utils.system.availableProcessors
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.Callable
import java.util.concurrent.CountDownLatch
import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.SynchronousQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit
/**
* ThreadPoolBuilder DSL 与预设工厂的测试
*/
class ThreadPoolBuilderTest {
@Test
fun testDslBuild() {
val pool = threadPool("dsl-test") {
corePoolSize = 2
maximumPoolSize = 4
boundedQueue(10)
keepAliveSeconds = 30
allowCoreThreadTimeout = true
}
try {
assertEquals(2, pool.corePoolSize)
assertEquals(4, pool.maximumPoolSize)
assertEquals(10, pool.queue.remainingCapacity())
assertTrue(pool.queue is ArrayBlockingQueue<*>)
assertTrue(pool.allowsCoreThreadTimeOut())
} finally {
pool.shutdown()
}
}
@Test
fun testDefaultQueueIsUnbounded() {
val pool = threadPool("unbounded-test")
try {
assertEquals(Int.MAX_VALUE, pool.queue.remainingCapacity())
} finally {
pool.shutdown()
}
}
@Test
fun testFixedPool() {
val pool = fixedThreadPool(4, "fixed-test")
try {
assertEquals(4, pool.corePoolSize)
assertEquals(4, pool.maximumPoolSize)
} finally {
pool.shutdown()
}
}
@Test
fun testSinglePool() {
val pool = singleThreadPool("single-test")
try {
assertEquals(1, pool.corePoolSize)
assertEquals(1, pool.maximumPoolSize)
} finally {
pool.shutdown()
}
}
@Test
fun testCachedPool() {
val pool = cachedThreadPool("cached-test")
try {
assertEquals(0, pool.corePoolSize)
assertEquals(Int.MAX_VALUE, pool.maximumPoolSize)
assertTrue(pool.queue is SynchronousQueue<*>)
} finally {
pool.shutdown()
}
}
@Test
fun testIoPool() {
val pool = ioThreadPool("io-test")
try {
assertEquals(availableProcessors * 2, pool.corePoolSize)
assertEquals(availableProcessors * 4, pool.maximumPoolSize)
assertEquals(1024, pool.queue.remainingCapacity())
} finally {
pool.shutdown()
}
}
@Test
fun testCpuPool() {
val pool = cpuThreadPool("cpu-test")
try {
assertEquals(availableProcessors, pool.corePoolSize)
assertEquals(availableProcessors, pool.maximumPoolSize)
} finally {
pool.shutdown()
}
}
@Test
fun testDaemonThread() {
val pool = threadPool("daemon-test") {
corePoolSize = 1
maximumPoolSize = 1
daemon = true
}
try {
val future = pool.submit(Callable { Thread.currentThread().isDaemon })
assertTrue(future.get(5, TimeUnit.SECONDS))
} finally {
pool.shutdown()
}
}
@Test
fun testNonDaemonThread() {
val pool = threadPool("non-daemon-test") {
corePoolSize = 1
maximumPoolSize = 1
daemon = false
}
try {
val future = pool.submit(Callable { Thread.currentThread().isDaemon })
assertFalse(future.get(5, TimeUnit.SECONDS))
} finally {
pool.shutdown()
}
}
@Test
fun testThreadNaming() {
val pool = threadPool("naming-test") {
corePoolSize = 2
maximumPoolSize = 2
}
try {
val future = pool.submit(Callable { Thread.currentThread().name })
val name = future.get(5, TimeUnit.SECONDS)
assertNotNull(name)
assertTrue(name!!.contains("naming-test"))
} finally {
pool.shutdown()
}
}
@Test
fun testRejectedPolicy() {
val pool = threadPool("reject-test") {
corePoolSize = 1
maximumPoolSize = 1
boundedQueue(1)
rejectedHandler = ThreadPoolExecutor.AbortPolicy()
}
val release = CountDownLatch(1)
try {
// 任务1 占用唯一线程
pool.execute { release.await() }
// 任务2 占满队列
pool.execute { }
// 任务3 触发拒绝
assertThrows(RejectedExecutionException::class.java) {
pool.execute { }
}
} finally {
release.countDown()
pool.shutdown()
}
}
@Test
fun testScheduledPool() {
val pool = scheduledThreadPool(2, "scheduled-test")
try {
val latch = CountDownLatch(1)
pool.schedule({ latch.countDown() }, 50, TimeUnit.MILLISECONDS)
assertTrue(latch.await(3, TimeUnit.SECONDS))
} finally {
pool.shutdown()
}
}
}
@@ -0,0 +1,266 @@
/*
* 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.test
* CurrentFile ThreadPoolExtTest.kt
* LastUpdate 2026-10-19 20:58:00
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.thread
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.util.concurrent.Callable
import java.util.concurrent.CountDownLatch
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.TimeUnit
/**
* ThreadPoolExt 线程池扩展与 ThreadPoolMonitor 监控的测试
*/
class ThreadPoolExtTest {
// ---- shutdownGracefully ----
@Test
fun testShutdownGracefully() {
val pool = fixedThreadPool(2, "shutdown-test")
pool.execute { Thread.sleep(50) }
assertTrue(pool.shutdownGracefully(5, TimeUnit.SECONDS))
assertTrue(pool.isTerminated)
}
@Test
fun testShutdownAndAwait() {
val pool = fixedThreadPool(1, "shutdown-await-test")
pool.execute { }
pool.shutdownAndAwait(5, TimeUnit.SECONDS)
assertTrue(pool.isTerminated)
}
@Test
fun testShutdownAndAwaitTimeout() {
val pool = singleThreadPool("shutdown-timeout-test")
// 忙等任务不响应中断,shutdownNow 无法立即终止它
pool.execute {
val end = System.nanoTime() + 2_000_000_000L
while (System.nanoTime() < end) {
// 忙等,忽略中断
}
}
assertThrows(IllegalStateException::class.java) {
pool.shutdownAndAwait(100, TimeUnit.MILLISECONDS)
}
pool.shutdownNow()
}
// ---- Future 扩展 ----
@Test
fun testFutureAwait() {
val pool = singleThreadPool("await-test")
try {
val future = pool.submit(Callable { "result" })
assertEquals("result", future.await())
} finally {
pool.shutdown()
}
}
@Test
fun testFutureAwaitUnwrapException() {
val pool = singleThreadPool("unwrap-test")
try {
val future = pool.submit(Callable { throw IllegalArgumentException("boom") })
assertThrows(IllegalArgumentException::class.java) {
future.await()
}
} finally {
pool.shutdown()
}
}
@Test
fun testFutureAwaitWithTimeout() {
val pool = singleThreadPool("await-timeout-test")
try {
val future = pool.submit(Callable {
Thread.sleep(500)
"late"
})
assertThrows(java.util.concurrent.TimeoutException::class.java) {
future.await(100, TimeUnit.MILLISECONDS)
}
// 任务最终仍会完成
assertEquals("late", future.get(3, TimeUnit.SECONDS))
} finally {
pool.shutdown()
}
}
@Test
fun testGetOrNullTimeout() {
val pool = singleThreadPool("getornull-test")
try {
val future = pool.submit(Callable {
Thread.sleep(500)
1
})
assertNull(future.getOrNull(100, TimeUnit.MILLISECONDS))
assertEquals(1, future.get(3, TimeUnit.SECONDS))
} finally {
pool.shutdown()
}
}
@Test
fun testGetOrNullFailure() {
val pool = singleThreadPool("getornull-fail-test")
try {
val future = pool.submit(Callable { throw RuntimeException("fail") })
assertNull(future.getOrNull(3, TimeUnit.SECONDS))
} finally {
pool.shutdown()
}
}
@Test
fun testGetOrDefault() {
val pool = singleThreadPool("getordefault-test")
try {
val failing: java.util.concurrent.Future<Int> =
pool.submit(Callable<Int> { throw RuntimeException("fail") })
assertEquals(-1, failing.getOrDefault(-1, 3, TimeUnit.SECONDS))
val ok = pool.submit(Callable { 5 })
assertEquals(5, ok.getOrDefault(-1, 3, TimeUnit.SECONDS))
} finally {
pool.shutdown()
}
}
@Test
fun testCancelQuietly() {
val pool = singleThreadPool("cancel-test")
try {
val future = pool.submit(Callable {
Thread.sleep(500)
1
})
assertTrue(future.cancelQuietly())
assertTrue(future.isCancelled)
} finally {
pool.shutdown()
}
}
// ---- CompletableFuture ----
@Test
fun testCompletableFuture() {
val future = completableFuture { 1 + 1 }
assertEquals(2, future.get(3, TimeUnit.SECONDS))
}
@Test
fun testCompletableFutureWithExecutor() {
val pool = fixedThreadPool(2, "cf-test")
try {
val future = completableFuture(pool) { "exec" }
assertEquals("exec", future.get(3, TimeUnit.SECONDS))
} finally {
pool.shutdown()
}
}
@Test
fun testRunCompletableFuture() {
val latch = CountDownLatch(1)
val future = runCompletableFuture { latch.countDown() }
assertTrue(latch.await(3, TimeUnit.SECONDS))
assertNull(future.get(3, TimeUnit.SECONDS))
}
// ---- ThreadPoolMonitor ----
@Test
fun testSnapshot() {
val pool = fixedThreadPool(2, "snapshot-test")
try {
pool.invokeAll(listOf(Callable { 1 }, Callable { 2 }))
val snapshot = pool.snapshot()
assertEquals(2, snapshot.corePoolSize)
assertEquals(2, snapshot.maximumPoolSize)
assertEquals(2, snapshot.poolSize)
assertTrue(snapshot.completedTasks >= 2)
assertTrue(snapshot.totalTasks >= 2)
assertTrue(snapshot.utilization in 0.0..1.0)
assertTrue(snapshot.queueSize >= 0)
assertFalse(snapshot.isShutdown)
assertFalse(snapshot.isTerminated)
} finally {
pool.shutdown()
}
}
@Test
fun testSnapshotToString() {
val pool = fixedThreadPool(1, "snapshot-string-test")
try {
val text = pool.snapshot().toString()
assertTrue(text.startsWith("ThreadPoolSnapshot["))
assertTrue(text.contains("size="))
assertTrue(text.contains("queue="))
} finally {
pool.shutdown()
}
}
@Test
fun testReport() {
val pool = fixedThreadPool(1, "report-test")
try {
val report = pool.report()
assertTrue(report.startsWith("ThreadPoolSnapshot["))
} finally {
pool.shutdown()
}
}
@Test
fun testMonitorPeriodic() {
val pool = fixedThreadPool(2, "monitor-test")
val scheduler = ScheduledThreadPoolExecutor(1)
val latch = CountDownLatch(2)
val handle = pool.monitor(30, TimeUnit.MILLISECONDS, scheduler = scheduler) { snapshot ->
if (snapshot.completedTasks >= 0) {
latch.countDown()
}
}
try {
assertTrue(latch.await(5, TimeUnit.SECONDS), "应至少收到 2 次监控回调")
} finally {
handle.cancel(true)
scheduler.shutdownNow()
pool.shutdown()
}
}
}
@@ -0,0 +1,228 @@
/*
* 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.test
* CurrentFile ThreadToolsTest.kt
* LastUpdate 2026-10-19 20:58:00
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.thread
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertSame
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
/**
* ThreadUtils / ThreadExt / ThreadLocalDelegates 的测试
*/
class ThreadToolsTest {
// ---- ThreadLocal 属性委托(每个测试方法独立实例,互不影响) ----
private var userValue: Long by threadLocal { 0L }
private var nullableValue: String? by nullableThreadLocal()
/** 将已有 ThreadLocal 实例包装为属性委托 */
private var delegatedValue: String? by ThreadLocal<String?>().asDelegate()
// ---- ThreadUtils ----
@Test
fun testSleepQuietlyMillis() {
val start = System.nanoTime()
ThreadUtils.sleepQuietly(100)
assertTrue(System.nanoTime() - start >= 90_000_000L, "应至少休眠 100ms")
}
@Test
fun testSleepQuietlyTimeUnit() {
val start = System.nanoTime()
ThreadUtils.sleepQuietly(50, TimeUnit.MILLISECONDS)
assertTrue(System.nanoTime() - start >= 40_000_000L, "应至少休眠 50ms")
}
@Test
fun testCurrentThreadNameProperty() {
assertEquals(Thread.currentThread().name, ThreadUtils.currentThreadName)
val old = ThreadUtils.currentThreadName
try {
ThreadUtils.currentThreadName = "renamed-test"
assertEquals("renamed-test", Thread.currentThread().name)
} finally {
ThreadUtils.currentThreadName = old
}
}
@Test
fun testCurrentThreadInfo() {
assertEquals(Thread.currentThread().priority, ThreadUtils.currentThreadPriority)
assertFalse(ThreadUtils.isCurrentDaemon())
assertEquals(Thread.currentThread().name == "main", ThreadUtils.isMainThread())
assertTrue(ThreadUtils.currentStackTrace().isNotEmpty())
assertSame(Thread.currentThread().threadGroup, ThreadUtils.currentThreadGroup())
assertTrue(ThreadUtils.activeThreadCount() >= 1)
}
@Test
fun testActiveThreads() {
val threads = ThreadUtils.activeThreads()
assertTrue(threads.any { it === Thread.currentThread() }, "活跃线程应包含当前线程")
}
@Test
fun testAllThreadsDump() {
val dump = ThreadUtils.allThreadsDump()
assertTrue(dump.contains(Thread.currentThread().name), "全线程转储应包含当前线程名")
}
@Test
fun testCurrentThreadDump() {
val dump = ThreadUtils.currentThreadDump()
assertTrue(dump.contains("testCurrentThreadDump"), "当前线程转储应包含测试方法名")
}
// ---- ThreadExt ----
@Test
fun testStartThread() {
val latch = CountDownLatch(1)
val thread = Runnable { latch.countDown() }.startThread("start-test", daemon = true)
assertTrue(latch.await(3, TimeUnit.SECONDS))
assertTrue(thread.isDaemon)
assertEquals("start-test", thread.name)
thread.joinQuietly(2000)
}
@Test
fun testAsThreadNotStarted() {
val thread = Runnable { }.asThread("no-start")
assertFalse(thread.isAlive)
assertTrue(thread.isDaemon)
assertEquals("no-start", thread.name)
}
@Test
fun testDaemonAndUserThread() {
val latch = CountDownLatch(2)
val daemon = daemonThread("daemon-t") { latch.countDown() }
val user = userThread("user-t") { latch.countDown() }
assertTrue(latch.await(3, TimeUnit.SECONDS))
assertTrue(daemon.isDaemon)
assertFalse(user.isDaemon)
daemon.joinQuietly(2000)
user.joinQuietly(2000)
}
@Test
fun testDaemonThreadNotStarted() {
val thread = daemonThread("no-start-daemon", start = false) { }
assertFalse(thread.isAlive)
assertTrue(thread.isDaemon)
}
@Test
fun testOnUncaughtHandler() {
val latch = CountDownLatch(1)
val captured = AtomicReference<Throwable?>()
val handler = uncaughtExceptionHandler { _, e ->
captured.set(e)
latch.countDown()
}
Runnable { throw IllegalStateException("boom") }
.asThread("crash-test", uncaughtHandler = handler)
.start()
assertTrue(latch.await(3, TimeUnit.SECONDS))
assertTrue(captured.get() is IllegalStateException)
assertEquals("boom", captured.get()!!.message)
}
@Test
fun testStartIfNotStarted() {
val thread = Runnable { }.asThread("idempotent-start")
assertSame(thread, thread.startIfNotStarted())
assertTrue(thread.isAlive)
thread.joinQuietly(2000)
assertFalse(thread.isAlive)
// 已终止线程再次调用不应抛异常
assertSame(thread, thread.startIfNotStarted())
}
@Test
fun testSleepQuietlyExt() {
val start = System.nanoTime()
Thread.currentThread().sleepQuietly(50)
assertTrue(System.nanoTime() - start >= 40_000_000L, "应至少休眠 50ms")
}
@Test
fun testDumpStackTrace() {
val dump = Thread.currentThread().dumpStackTrace()
assertTrue(dump.contains(Thread.currentThread().name))
assertTrue(dump.contains("testDumpStackTrace"))
}
@Test
fun testCurrentThreadTopLevel() {
assertSame(Thread.currentThread(), currentThread())
}
// ---- ThreadLocalDelegates ----
@Test
fun testThreadLocalSameThread() {
assertNull(nullableValue)
nullableValue = "hello"
assertEquals("hello", nullableValue)
assertEquals(0L, userValue)
userValue = 42L
assertEquals(42L, userValue)
}
@Test
fun testThreadLocalIsolation() {
val latch = CountDownLatch(1)
val threadValues = ConcurrentLinkedQueue<Long>()
// 主线程先设置自己的值
userValue = 100L
val thread = daemonThread("tl-isolation") {
assertEquals(0L, userValue, "新线程应获得初始值而非主线程的值")
userValue = 7L
threadValues.add(userValue)
latch.countDown()
}
assertTrue(latch.await(3, TimeUnit.SECONDS))
thread.joinQuietly(2000)
assertEquals(100L, userValue, "主线程的值不受子线程影响")
assertEquals(listOf(7L), threadValues.toList())
}
@Test
fun testAsDelegateProperty() {
assertNull(delegatedValue)
delegatedValue = "set"
assertEquals("set", delegatedValue)
}
}