Compare commits

..
Author SHA1 Message Date
minglipro 31987b9b14 a 2026-10-20 20:05:40 +08:00
minglipro 474071e43b 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 个单元测试
2026-10-19 21:09:57 +08:00
minglipro 6624c00553 feat(json): 修复Jackson3JsonApi Jvm 签名
Gitea Actions Build / Build (push) Canceled after 0s
2026-10-12 14:01:13 +08:00
minglipro 2c423c4aff feat(pool): 完善对象池并新增可复用线程池
Gitea Actions Build / Build (push) Canceled after 0s
pool:
- ObjectPool 移除 @Deprecated("未实现") 标记,完成实现
  * close() 正确设置关闭标志、销毁空闲对象并 signalAll 唤醒等待者
  * borrow() 修复竞态:循环重取避免 poll 返回 null;创建失败回滚计数
  * 区分「无限等待 / 立即超时 / 有限等待」三种超时语义
  * returnObject() 拒绝外来对象或已关闭状态,直接销毁以防污染
  * 空闲队列由 ConcurrentLinkedQueue 改为 ArrayDeque,所有访问统一持锁,
    移除冗余的 AtomicInteger;idleSize / activeSize / totalSize 返回精确值
  * 新增 snapshot() 提供 idle/active/total/closed 一致快照
- 新增 Pool.kt:抽取通用接口,use() 使用 try/finally 保证归还,
  新增 useResult() 支持带返回值场景
- 新增 ObjectPoolData.kt:池对象元数据包装,提供 release() 语法糖
- 新增 ThreadPool.kt:可复用线程池
  * 池对象为 Worker(长期存活的守护线程 + LinkedBlockingQueue 任务队列),
    线程通过循环消费任务实现真正复用,保留 ThreadLocal 状态
  * 提供 execute / call / submit / submitRunnable 四种任务投递方式
  * submit 返回 CompletableFuture,任务完成后自动归还 Worker
  * 内置 submitted/completed/failed 计数与 uncaughtHandler 兜底,
    任务异常不会导致 Worker 线程死亡
  * 提供 defaultPool / fixed / single 静态工厂与 closeAndAwait 优雅关闭

json:
- Jackson3JsonApi / JacksonJsonApi 暴露 getObjectMapper() 便于外部扩展

metadata:
- MingliUtilsMetaData 改为 data class,获得 equals/hashCode/copy/toString

mybatisplus:
- 修正 BaseMapperQuery @Deprecated 的 ReplaceWith 表达式(去掉多余的 <*>)
2026-10-12 13:57:14 +08:00
31 changed files with 4223 additions and 624 deletions
+2 -2
View File
@@ -16,10 +16,10 @@
# ProjectName mingli-utils # ProjectName mingli-utils
# ModuleName mingli-utils # ModuleName mingli-utils
# CurrentFile gradle.properties # CurrentFile gradle.properties
# LastUpdate 2026-10-11 16:28:05 # LastUpdate 2026-10-12 13:57:03
# UpdateUser MingLiPro # UpdateUser MingLiPro
# #
JDKVERSIONS=17 JDKVERSIONS=17
GROUPSID=com.mingliqiye.utils GROUPSID=com.mingliqiye.utils
ARTIFACTID=mingli-utils ARTIFACTID=mingli-utils
VERSIONS=5.3.1 VERSIONS=5.3.2
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile Jackson3JsonApi.kt * CurrentFile Jackson3JsonApi.kt
* LastUpdate 2026-06-21 10:40:58 * LastUpdate 2026-10-12 13:59:59
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -44,9 +44,9 @@ class Jackson3JsonApi : JsonApi {
private var _prObjectMapper: ObjectMapper? = null private var _prObjectMapper: ObjectMapper? = null
private var objectMapper: ObjectMapper var objectMapper: ObjectMapper
get() = get() get() = get()
set(value) = set(value) private set(value) = set(value)
constructor(objectMapper: ObjectMapper) { constructor(objectMapper: ObjectMapper) {
_prObjectMapper = objectMapper _prObjectMapper = objectMapper
@@ -178,8 +178,7 @@ class Jackson3JsonApi : JsonApi {
return objectMapper.convertValue(source, destinationClass) return objectMapper.convertValue(source, destinationClass)
} catch (e: Exception) { } catch (e: Exception) {
throw JsonException( throw JsonException(
"Failed to convert from ${source.javaClass.simpleName} to ${destinationClass.simpleName}", "Failed to convert from ${source.javaClass.simpleName} to ${destinationClass.simpleName}", e
e
) )
} }
} }
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile JacksonJsonApi.kt * CurrentFile JacksonJsonApi.kt
* LastUpdate 2026-10-11 16:54:15 * LastUpdate 2026-10-12 10:48:31
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -51,6 +51,8 @@ class JacksonJsonApi : JsonApi {
this.objectMapper = ObjectMapper() this.objectMapper = ObjectMapper()
} }
fun getObjectMapper() = objectMapper
/** /**
* 使用指定的ObjectMapper构造实例 * 使用指定的ObjectMapper构造实例
* *
@@ -16,18 +16,18 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile MingliUtilsMetaData.kt * CurrentFile MingliUtilsMetaData.kt
* LastUpdate 2026-03-11 08:46:40 * LastUpdate 2026-10-12 13:32:30
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.metadata package com.mingliqiye.utils.metadata
class MingliUtilsMetaData { data class MingliUtilsMetaData(
var buildTime: String = "" var buildTime: String = "",
var groupId: String = "" var groupId: String = "",
var artifactId: String = "" var artifactId: String = "",
var version: String = "" var version: String = "",
var buildJdkVersion: String = "" var buildJdkVersion: String = "",
var author: String = "" var author: String = "",
var website: String = "" var website: String = "",
} )
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile BaseMapperQuery.kt * CurrentFile BaseMapperQuery.kt
* LastUpdate 2026-02-06 13:15:11 * LastUpdate 2026-10-12 13:33:03
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -36,7 +36,7 @@ import com.baomidou.mybatisplus.extension.kotlin.KtUpdateWrapper
@Deprecated( @Deprecated(
"rename to FastBaseMapper", "rename to FastBaseMapper",
replaceWith = ReplaceWith( replaceWith = ReplaceWith(
expression = "FastBaseMapper<*>", expression = "FastBaseMapper",
imports = ["com.mingliqiye.utils.mybatisplus.FastBaseMapper"] imports = ["com.mingliqiye.utils.mybatisplus.FastBaseMapper"]
), ),
level = DeprecationLevel.WARNING level = DeprecationLevel.WARNING
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile NettyUtils.kt * CurrentFile NettyUtils.kt
* LastUpdate 2026-06-27 21:40:00 * LastUpdate 2026-10-20 20:05:37
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -323,7 +323,7 @@ fun ByteBuf.releaseSafely(): Boolean {
*/ */
fun ByteBuf.tryRelease(): Boolean { fun ByteBuf.tryRelease(): Boolean {
return try { return try {
if (refCnt() > 0) release() else false refCnt() > 0 && release()
} catch (e: Exception) { } catch (e: Exception) {
false false
} }
@@ -1,5 +1,5 @@
/* /*
* Copyright 2025 mingliqiye * Copyright 2026 mingliqiye
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@@ -16,7 +16,7 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile OsPath.kt * CurrentFile OsPath.kt
* LastUpdate 2025-09-18 09:47:43 * LastUpdate 2026-10-20 20:05:37
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@@ -26,8 +26,7 @@ package com.mingliqiye.utils.path
import java.io.File import java.io.File
import java.net.URI import java.net.URI
import java.nio.file.Path import java.nio.file.*
import java.nio.file.Paths
import java.util.* import java.util.*
import java.util.function.Consumer import java.util.function.Consumer
@@ -40,6 +39,41 @@ class OsPath private constructor(private val path: Path) : Path by path {
return path.spliterator() return path.spliterator()
} }
override fun startsWith(other: String): Boolean {
return path.startsWith(other)
}
override fun endsWith(other: String): Boolean {
return path.endsWith(other)
}
override fun resolve(other: String): Path {
return path.resolve(other)
}
override fun resolveSibling(other: Path): Path {
return path.resolveSibling(other)
}
override fun resolveSibling(other: String): Path {
return path.resolveSibling(other)
}
override fun toFile(): File {
return path.toFile()
}
override fun register(
watcher: WatchService,
vararg events: WatchEvent.Kind<*>,
): WatchKey {
return path.register(watcher, *events)
}
override fun iterator(): MutableIterator<Path> {
return path.iterator()
}
companion object { companion object {
@JvmStatic @JvmStatic
fun of(path: String): OsPath { fun of(path: String): OsPath {
@@ -16,129 +16,192 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile ObjectPool.kt * CurrentFile ObjectPool.kt
* LastUpdate 2026-10-02 16:19:05 * LastUpdate 2026-10-12 13:57:11
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.pool package com.mingliqiye.utils.pool
import com.mingliqiye.utils.require.Require.require import com.mingliqiye.utils.require.Require.require
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.locks.Condition import java.util.concurrent.locks.Condition
import java.util.concurrent.locks.ReentrantLock import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock import kotlin.concurrent.withLock
@Deprecated("未实现") /**
* 通用对象池抽象实现。
*
* 支持最小空闲数量、最大容量、超时借用与自动回收。
* 子类只需实现 [init] 与 [destroy] 即可完成对象的创建与销毁。
*
* 线程安全:内部通过 [ReentrantLock] + [Condition] 协调借出/归还的等待与唤醒。
*
* @param T 池中管理的对象类型
* @property maxSize 池允许存在的对象总数上限(含已借出),必须大于 0
* @property minSize 池需要保持的最小空闲对象数,[borrow] 归还会在低于该值时补充
* @property initialSize 初始化时预热的对象数量,必须 >= [minSize] 且 <= [maxSize]
*/
abstract class ObjectPool<T>( abstract class ObjectPool<T>(
private val maxSize: Int = Int.MAX_VALUE, private val maxSize: Int = Int.MAX_VALUE,
private val minSize: Int = 0, private val minSize: Int = 0,
private val initialSize: Int = 1, private val initialSize: Int = 1,
) : Pool<T> { ) : Pool<T> {
/**
* 已创建(含空闲与借出)对象的总数,用于容量控制。
* 所有读写均在 [lock] 内完成,保证与 [borrowedCount]、[pool] 一致。
*/
private var createdCount: Int = 0
private val initialCount = AtomicInteger(0) /** 当前已借出、尚未归还的对象数量([lock] 保护) */
private val pool = ConcurrentLinkedQueue<ObjectPoolData<T>>() private var borrowedCount: Int = 0
/**
* 空闲对象队列。全部访问均在 [lock] 内完成,
* 因此 [ArrayDeque.size] 即为精确空闲数。
*/
private val pool = ArrayDeque<ObjectPoolData<T>>()
/** 池是否已关闭 */
private val isClosed = AtomicBoolean(false) private val isClosed = AtomicBoolean(false)
private val lock = ReentrantLock() private val lock = ReentrantLock()
private val notEmpty: Condition = lock.newCondition() private val notEmpty: Condition = lock.newCondition()
private val notFull: Condition = lock.newCondition()
init { init {
require(maxSize >= minSize) require(maxSize >= minSize)
require(initialSize >= minSize) require(initialSize >= minSize)
require(initialSize <= maxSize)
require(maxSize > 0) require(maxSize > 0)
repeat(initialSize) { repeat(initialSize) {
pool.add(init(initialCount.getAndIncrement())) pool.addLast(init(createdCount++))
} }
} }
/**
* 关闭对象池:销毁所有空闲对象,唤醒所有等待者。
* 已借出的对象在归还时会被直接销毁。
*/
override fun close() { override fun close() {
for (poolData in pool) { lock.withLock {
destroy(poolData) if (!isClosed.compareAndSet(false, true)) {
return
}
while (pool.isNotEmpty()) {
val data = pool.removeFirst()
runCatching { destroy(data) }
createdCount--
}
notEmpty.signalAll()
notFull.signalAll()
} }
} }
/**
* 从池中借出一个对象。
*
* 若池中有空闲对象则直接返回;否则在未达 [maxSize] 时新建;
* 达到上限时根据 [timeoutMillis] 阻塞等待归还,超时抛出 [IllegalStateException]。
*
* @param timeoutMillis 等待超时(毫秒)。<= 0 表示无限等待。
*/
override fun borrow(timeoutMillis: Long): ObjectPoolData<T> { override fun borrow(timeoutMillis: Long): ObjectPoolData<T> {
lock.withLock { lock.withLock {
var remainingNanos = if (timeoutMillis > 0) TimeUnit.MILLISECONDS.toNanos(timeoutMillis) else -1L
while (true) {
if (isClosed.get()) { if (isClosed.get()) {
throw IllegalStateException("Object pool closed") throw IllegalStateException("Object pool closed")
} }
pool.poll()?.let { return it }
if (initialCount.get() < maxSize) { // 1. 优先取空闲对象
return init(initialCount.getAndIncrement()) if (pool.isNotEmpty()) {
val data = pool.removeFirst()
borrowedCount++
return data
}
// 2. 池未满则创建新对象
if (createdCount < maxSize) {
val id = createdCount++
val data = try {
init(id)
} catch (e: Throwable) {
createdCount--
throw e
}
borrowedCount++
return data
} }
// 3. 池已满且无空闲,等待归还 // 3. 池已满且无空闲,等待归还
if (timeoutMillis <= 0) { if (remainingNanos < 0) {
// 无限等待 notEmpty.await()
while (pool.isEmpty()) { } else if (remainingNanos == 0L) {
notEmpty.await() // 释放锁并等待 throw IllegalStateException("Timeout waiting for object from pool")
} } else {
return pool.poll() remainingNanos = notEmpty.awaitNanos(remainingNanos)
} if (remainingNanos <= 0L) {
// 有限时间等待
var remainingNanos = TimeUnit.MILLISECONDS.toNanos(timeoutMillis)
while (pool.isEmpty()) {
if (remainingNanos <= 0) {
throw IllegalStateException("Timeout waiting for object from pool") throw IllegalStateException("Timeout waiting for object from pool")
} }
remainingNanos = notEmpty.awaitNanos(remainingNanos)
} }
return pool.poll() }
} }
} }
/**
* 归还对象到池中。
* 若池已关闭或对象不属于当前池,则直接销毁;否则回填到空闲队列并唤醒等待者。
*/
override fun returnObject(obj: ObjectPoolData<T>) { override fun returnObject(obj: ObjectPoolData<T>) {
lock.withLock { lock.withLock {
if (isClosed.get()) { borrowedCount--
throw InterruptedException("Object pool closed")
if (isClosed.get() || obj.objectPool !== this) {
runCatching { destroy(obj) }
createdCount--
notFull.signal()
return
} }
pool.add(obj)
pool.addLast(obj)
notEmpty.signal() notEmpty.signal()
} }
} }
/**
* 当前空闲对象数量(精确值)。
* 通过短暂持锁读取,与 [activeSize]/[totalSize] 各自独立但均为调用瞬间的真实值。
*/
fun idleSize(): Int = lock.withLock { pool.size }
/** 当前已借出、尚未归还的对象数量(精确值) */
fun activeSize(): Int = lock.withLock { borrowedCount }
/** 已创建对象总数,含空闲与借出(精确值) */
fun totalSize(): Int = lock.withLock { createdCount }
/** 池是否已关闭 */
fun closed(): Boolean = isClosed.get()
/**
* 一次性读取空闲 / 借出 / 总数 的一致快照(同一把锁内)。
*
* 相比分别调用三个方法,可避免三者之间因并发导致的不自洽
* (例如 `idle + active != total`)。
*/
fun snapshot(): PoolSnapshot = lock.withLock {
PoolSnapshot(idle = pool.size, active = borrowedCount, total = createdCount, closed = isClosed.get())
} }
/**
interface Pool<T> { * 池状态快照。
fun close() * @property idle 空闲对象数
fun borrow(timeoutMillis: Long): ObjectPoolData<T> * @property active 已借出对象数
fun borrow(): ObjectPoolData<T> = borrow(0) * @property total 已创建对象总数(= idle + active)
fun returnObject(obj: ObjectPoolData<T>) * @property closed 池是否已关闭
fun use(funs: (ObjectPoolData<T>) -> Unit) = use(0, funs) */
fun init(id: Int): ObjectPoolData<T> data class PoolSnapshot(val idle: Int, val active: Int, val total: Int, val closed: Boolean)
fun destroy(data: ObjectPoolData<T>)
fun use(timeoutMillis: Long, funs: (ObjectPoolData<T>) -> Unit) {
val i = borrow(timeoutMillis)
funs(i)
returnObject(i)
}
}
data class ObjectPoolData<T>(
val obj: T,
val objectPool: ObjectPool<T>,
val id: Int = obj.hashCode(),
val name: String = "",
)
class TheardPool : ObjectPool<Thread>() {
override fun init(id: Int): ObjectPoolData<Thread> {
return ObjectPoolData(
Thread().apply {
name = "TheardPool $id"
},
this
)
}
override fun destroy(data: ObjectPoolData<Thread>) {
data.obj.interrupt()
}
} }
@@ -0,0 +1,41 @@
/*
* 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 ObjectPoolData.kt
* LastUpdate 2026-10-12 13:43:53
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.pool
/**
* 池对象的元数据包装。
*
* @property obj 实际对象
* @property objectPool 归属的对象池
* @property id 池内编号,默认取 [obj] 的 hashCode
* @property name 可选的名称,用于日志/调试
*/
data class ObjectPoolData<T>(
val obj: T,
val objectPool: ObjectPool<T>,
val id: Int = obj.hashCode(),
val name: String = "",
) {
/** 语法糖:归还到所属池 */
fun release() = objectPool.returnObject(this)
}
@@ -0,0 +1,73 @@
/*
* 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 Pool.kt
* LastUpdate 2026-10-12 13:43:53
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.pool
/**
* 对象池通用接口。
*/
interface Pool<T> {
/** 关闭池并释放全部资源 */
fun close()
/** 借出一个对象,[timeoutMillis] <= 0 表示无限等待 */
fun borrow(timeoutMillis: Long): ObjectPoolData<T>
/** 无限等待地借出一个对象 */
fun borrow(): ObjectPoolData<T> = borrow(0)
/** 归还对象 */
fun returnObject(obj: ObjectPoolData<T>)
/** 使用默认超时执行 [funs] */
fun use(funs: (ObjectPoolData<T>) -> Unit) = use(0, funs)
/** 创建一个新的池对象 */
fun init(id: Int): ObjectPoolData<T>
/** 销毁池对象 */
fun destroy(data: ObjectPoolData<T>)
/**
* 借出对象执行 [funs],无论是否抛出异常都会自动归还。
*/
fun use(timeoutMillis: Long, funs: (ObjectPoolData<T>) -> Unit) {
val data = borrow(timeoutMillis)
try {
funs(data)
} finally {
runCatching { returnObject(data) }
}
}
/**
* 借出对象执行 [funs] 并返回其结果,无论是否抛出异常都会自动归还。
*/
fun <R> useResult(timeoutMillis: Long = 0, funs: (ObjectPoolData<T>) -> R): R {
val data = borrow(timeoutMillis)
try {
return funs(data)
} finally {
runCatching { returnObject(data) }
}
}
}
@@ -15,10 +15,11 @@
* *
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile RandomBytes.kt * CurrentFile Random.kt
* LastUpdate 2026-10-11 17:11:11 * LastUpdate 2026-10-20 20:05:37
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
package com.mingliqiye.utils.random package com.mingliqiye.utils.random
import java.security.SecureRandom import java.security.SecureRandom
@@ -44,7 +45,7 @@ object Random {
* 通过lazy委托延迟初始化 * 通过lazy委托延迟初始化
*/ */
private val random: Random by lazy { private val random: Random by lazy {
Random Random.Default
} }
/** /**
@@ -1,229 +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 Require.kt
* LastUpdate 2026-02-24 09:03:42
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.require
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import org.slf4j.Logger
import java.lang.reflect.Constructor
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
import kotlin.reflect.KClass
/**
* 条件检查工具对象,提供多种重载的require方法用于参数验证和异常抛出
* 支持自定义异常类型、延迟消息构造和日志记录功能
*/
object Require {
@JvmStatic
var logger: Logger? = MingLiLoggerFactory.getLogger<Require>()
@JvmStatic
var isLogError = true
/**
* 检查条件是否满足,如果不满足则抛出指定类型的异常
* @param value 要检查的布尔条件
* @param throwable 异常类型Class对象
* @param layzMessage 延迟消息构造器
*/
@JvmStatic
@OptIn(ExperimentalContracts::class)
fun require(value: Boolean, throwable: Class<out Throwable>, layzMessage: RequireLayzMessageConstructor) {
contract {
returns() implies value
}
require(value, layzMessage.call(), throwable)
}
/**
* 检查条件是否满足,如果不满足则抛出指定类型的异常
* @param value 要检查的布尔条件
* @param throwable 异常类型KClass对象
* @param layzMessage 延迟消息构造器
*/
@JvmStatic
@OptIn(ExperimentalContracts::class)
fun require(value: Boolean, throwable: KClass<out Throwable>, layzMessage: RequireLayzMessageConstructor) {
contract {
returns() implies value
}
require(value, throwable.java, layzMessage)
}
/**
* 检查条件是否满足,如果不满足则抛出延迟构造的异常
* @param value 要检查的布尔条件
* @param layzThrowable 延迟异常构造器
*/
@JvmStatic
@OptIn(ExperimentalContracts::class)
fun require(value: Boolean, layzThrowable: RequireLayzExceptionConstructor) {
contract {
returns() implies value
}
if (!value) throwThrowable(layzThrowable.call())
}
/**
* 检查条件是否满足,如果不满足则抛出指定消息和类型的异常
* @param value 要检查的布尔条件
* @param message 异常消息
* @param throwable 异常类型Class对象
*/
@JvmStatic
@OptIn(ExperimentalContracts::class)
fun require(value: Boolean, message: String, throwable: Class<out Throwable>) {
contract {
returns() implies value
}
if (!value) throwThrowable(getExceptionConstructor(throwable).newInstance(message))
}
/**
* 检查条件是否满足,如果不满足则抛出指定消息和类型的异常
* @param value 要检查的布尔条件
* @param message 异常消息
* @param throwable 异常类型KClass对象
*/
@JvmStatic
@OptIn(ExperimentalContracts::class)
fun require(value: Boolean, message: String, throwable: KClass<out Throwable>) {
contract {
returns() implies value
}
require(value, message, throwable.java)
}
/**
* 抛出异常并在启用日志时记录错误信息
* @param throwable 要抛出的异常对象
*/
@JvmStatic
fun throwThrowable(throwable: Throwable) {
if (isLogError && logger != null) logger!!.error(throwable.message, throwable)
throw throwable
}
/**
* 内联函数版本的条件检查,支持泛型异常类型
* @param T 异常类型
* @param value 要检查的布尔条件
* @param message 异常消息
*/
@OptIn(ExperimentalContracts::class)
@JvmName("__inline_Require")
@JvmStatic
inline fun <reified T : Throwable> require(value: Boolean, message: String) {
contract {
returns() implies value
}
require(value, message, T::class.java)
}
/**
* 内联函数版本的条件检查,支持泛型异常类型和延迟消息构造
* @param T 异常类型
* @param value 要检查的布尔条件
* @param layzMessage 延迟消息构造器
*/
@OptIn(ExperimentalContracts::class)
@JvmName("__inline_Require")
@JvmStatic
inline fun <reified T : Throwable> require(value: Boolean, layzMessage: RequireLayzMessageConstructor) {
contract {
returns() implies value
}
if (!value) throwThrowable(getExceptionConstructor<T>().newInstance(layzMessage.call()))
}
/**
* 获取指定异常类型的构造函数(内联泛型版本)
* @param T 异常类型
* @return 异常类型的构造函数
*/
@JvmName("__inline_GetExceptionConstructor")
@JvmStatic
inline fun <reified T : Throwable> getExceptionConstructor(): Constructor<out T> =
getExceptionConstructor(T::class.java)
/**
* 获取指定异常类型的构造函数
* @param throwable 异常类型Class对象
* @return 异常类型的构造函数
*/
@JvmStatic
@JvmName("__GetExceptionConstructor")
fun <T : Throwable> getExceptionConstructor(throwable: Class<out T>): Constructor<out T> =
throwable.getConstructor(String::class.java)
/**
* 获取指定异常类型的构造函数
* @param throwable 异常类型KClass对象
* @return 异常类型的构造函数
*/
@JvmStatic
@JvmName("__GetExceptionConstructor")
fun <T : Throwable> getExceptionConstructor(throwable: KClass<out T>): Constructor<out T> =
getExceptionConstructor(throwable.java)
/**
* 基础条件检查方法,不满足条件时抛出IllegalArgumentException
* @param value 要检查的布尔条件
*/
@OptIn(ExperimentalContracts::class)
@JvmStatic
fun require(value: Boolean) {
contract {
returns() implies value
}
require(value, "the require conditions are not met.")
}
/**
* 使用延迟消息构造器进行条件检查,不满足时抛出IllegalArgumentException
* @param value 要检查的布尔条件
* @param layzMessage 延迟消息构造器
*/
@OptIn(ExperimentalContracts::class)
@JvmStatic
fun requireLayzMessage(value: Boolean, layzMessage: RequireLayzMessageConstructor) {
contract {
returns() implies value
}
require(value, IllegalArgumentException::class.java, layzMessage)
}
/**
* 带消息的条件检查方法,不满足条件时抛出IllegalArgumentException
* @param value 要检查的布尔条件
* @param message 异常消息
*/
@OptIn(ExperimentalContracts::class)
@JvmStatic
fun require(value: Boolean, message: String) {
contract {
returns() implies value
}
if (!value) throwThrowable(getExceptionConstructor(IllegalArgumentException::class.java).newInstance(message))
}
}
@@ -0,0 +1,190 @@
/*
* 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 RequireTrue.kt
* LastUpdate 2026-10-20 20:05:24
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.require
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
const val DEFAULT_MESSAGE = "required fail"
class Required<T : Throwable>(private val newException: (message: String) -> T) {
@OptIn(ExperimentalContracts::class)
fun requireTrue(value: Boolean, message: String) {
contract {
returns() implies value
}
requireTrue(value) { message }
}
@OptIn(ExperimentalContracts::class)
fun requireTrue(value: Boolean) {
contract {
returns() implies value
}
requireTrue(value) { DEFAULT_MESSAGE }
}
@OptIn(ExperimentalContracts::class)
fun requireTrue(value: Boolean, lazyMessage: () -> String) {
contract {
returns() implies value
}
if (!value) {
throw newException(lazyMessage())
}
}
}
fun newRequired(): Required<IllegalArgumentException> {
return newRequired<IllegalArgumentException>()
}
fun <T : Throwable> newRequired(clazz: Class<T>): Required<T> {
return Required {
newException(clazz, it)
}
}
inline fun <reified T : Throwable> newRequired(): Required<T> {
return newRequired(T::class.java)
}
fun <T : Throwable> newException(clazz: Class<T>, msg: String): T = try {
val constructor = clazz.getConstructor(String::class.java).also {
check(!java.lang.reflect.Modifier.isAbstract(clazz.modifiers)) {
"${clazz.name} 是抽象类,无法实例化"
}
}
constructor.newInstance(msg)
} catch (e: ReflectiveOperationException) {
throw IllegalStateException("无法实例化 ${clazz.name}", e)
}
@OptIn(ExperimentalContracts::class)
fun <T : Throwable> requireTrue(value: Boolean, clazz: Class<T>, lazyMessage: () -> String) {
contract {
returns() implies value
}
if (!value) {
throw newException(clazz, lazyMessage())
}
}
@OptIn(ExperimentalContracts::class)
inline fun <reified T : Throwable> requireTrue(value: Boolean, noinline lazyMessage: () -> String) {
contract {
returns() implies value
}
requireTrue(value, T::class.java, lazyMessage)
}
@OptIn(ExperimentalContracts::class)
fun <T : Throwable> Boolean.requireTrue(clazz: Class<T>, lazyMessage: () -> String) {
contract {
returns() implies this@requireTrue
}
requireTrue(this, clazz, lazyMessage)
}
@OptIn(ExperimentalContracts::class)
fun <T : Throwable> Boolean.requireTrue(clazz: Class<T>, message: String) {
contract {
returns() implies this@requireTrue
}
requireTrue(this, clazz) {
message
}
}
@OptIn(ExperimentalContracts::class)
fun <T : Throwable> requireTrue(value: Boolean, clazz: Class<T>, message: String) {
contract {
returns() implies value
}
requireTrue(value, clazz) { message }
}
@OptIn(ExperimentalContracts::class)
inline fun <reified T : Throwable> requireTrue(value: Boolean, message: String) {
contract {
returns() implies value
}
requireTrue(value, T::class.java) { message }
}
@OptIn(ExperimentalContracts::class)
inline fun <reified T : Throwable> Boolean.requireTrue(noinline lazyMessage: () -> String) {
contract {
returns() implies this@requireTrue
}
requireTrue(this, T::class.java, lazyMessage)
}
@OptIn(ExperimentalContracts::class)
inline fun <reified T : Throwable> Boolean.requireTrue(message: String) {
contract {
returns() implies this@requireTrue
}
requireTrue(this, T::class.java, message)
}
@OptIn(ExperimentalContracts::class)
fun <T : Throwable> requireTrue(value: Boolean, clazz: Class<T>) {
contract {
returns() implies value
}
requireTrue(value, clazz) { DEFAULT_MESSAGE }
}
@OptIn(ExperimentalContracts::class)
inline fun <reified T : Throwable> requireTrue(value: Boolean) {
contract {
returns() implies value
}
requireTrue(value, T::class.java) { DEFAULT_MESSAGE }
}
@OptIn(ExperimentalContracts::class)
fun <T : Throwable> Boolean.requireTrue(clazz: Class<T>) {
contract {
returns() implies this@requireTrue
}
requireTrue(this, clazz) { DEFAULT_MESSAGE }
}
@OptIn(ExperimentalContracts::class)
inline fun <reified T : Throwable> Boolean.requireTrue() {
contract {
returns() implies this@requireTrue
}
requireTrue(this, T::class.java) { DEFAULT_MESSAGE }
}
@@ -0,0 +1,23 @@
/*
* 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 Required.kt
* LastUpdate 2026-10-20 19:58:06
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.require
File diff suppressed because it is too large Load Diff
@@ -16,444 +16,271 @@
* ProjectName mingli-utils * ProjectName mingli-utils
* ModuleName mingli-utils.main * ModuleName mingli-utils.main
* CurrentFile SystemUtil.kt * CurrentFile SystemUtil.kt
* LastUpdate 2026-03-27 09:35:40 * LastUpdate 2026-10-20 18:54:24
* UpdateUser MingLiPro * UpdateUser MingLiPro
*/ */
@file:JvmName("SystemUtils") @file:JvmName("SystemUtils")
package com.mingliqiye.utils.system package com.mingliqiye.utils.system
import java.lang.management.ManagementFactory
import java.net.* import java.net.*
import java.util.*
import com.mingliqiye.utils.random.Random.nextBytes as randomByte import com.mingliqiye.utils.random.Random.nextBytes as randomByte
private val UNIX_PREFIXES = arrayOf("Linux", "AIX", "SunOS", "Mac OS X", "FreeBSD")
private val HEX_UPPER: Array<String> = Array(256) { "%02X".format(it) }
private fun <T> Enumeration<T>?.toList(): List<T> =
if (this == null) emptyList() else Collections.list(this)
/** /**
* 操作系统名称属性,延迟初始化 * 操作系统名称属性,延迟初始化
*/ */
val osName: String? by lazy { val osName: String? by lazy {
System.getProperties().getProperty("os.name") runCatching { System.getProperty("os.name") }.getOrNull()
} }
/** /**
* 判断当前操作系统是否为Windows系统 * 判断当前操作系统是否为 Windows
*
* @return 如果是Windows系统返回true,否则返回false
*/ */
val isWindows: Boolean by lazy { val isWindows: Boolean by lazy {
osName != null && osName!!.startsWith("Windows") osName?.startsWith("Windows") == true
} }
/** /**
* 判断当前操作系统是否为Mac系统 * 判断当前操作系统是否为 Mac
*
* @return 如果是Mac系统返回true,否则返回false
*/ */
val isMac: Boolean by lazy { val isMac: Boolean by lazy {
osName != null && osName!!.startsWith("Mac") osName?.startsWith("Mac") == true
} }
/** /**
* 判断当前操作系统是否为Unix/Linux系统 * 判断当前操作系统是否为 Unix/Linux(含 macOS)
*
* @return 如果是Unix/Linux系统返回true,否则返回false
*/ */
val isUnix: Boolean by lazy { val isUnix: Boolean by lazy {
if (osName == null) { val name = osName ?: return@lazy false
false UNIX_PREFIXES.any { name.startsWith(it) }
} else {
(osName!!.startsWith("Linux") || osName!!.startsWith("AIX") || osName!!.startsWith("SunOS") || osName!!.startsWith(
"Mac OS X"
) || osName!!.startsWith(
"FreeBSD"
))
}
} }
/** /**
* JDK 版本号属性,延迟初始化 * JDK 版本号属性,延迟初始化
*/ */
val jdkVersion: String? by lazy { val jdkVersion: String? by lazy {
System.getProperty("java.specification.version") runCatching { System.getProperty("java.specification.version") }.getOrNull()
} }
/** /**
* Java版本号的整数形式属性,延迟初始化 * Java 版本号的主版本整数,延迟初始化
*
* 同时兼容 `1.8` 旧式版本号与 `9` / `17` / `100` 等新式版本号。
*
* @throws IllegalStateException 无法解析出整数版本时抛出
*/ */
val javaVersionAsInteger: Int by lazy { val javaVersionAsInteger: Int by lazy {
val version = jdkVersion val version = jdkVersion
if (version == null || version.isEmpty()) { if (version.isNullOrBlank()) {
throw IllegalStateException( throw IllegalStateException(
"Unable to determine Java version from property 'java.specification.version'" "Unable to determine Java version from property 'java.specification.version'"
) )
} }
val normalized = if (version.startsWith("1.")) version.substring(2) else version
val uversion: String = if (version.startsWith("1.")) { val major = normalized.substringBefore('.').substringBefore('-')
if (version.length < 3) { major.toIntOrNull()
throw IllegalStateException( ?: throw IllegalStateException("Invalid Java version format: $version")
"Invalid Java version format: $version"
)
}
version[2] + ""
} else {
if (version.length < 2) {
throw IllegalStateException(
"Invalid Java version format: $version"
)
}
version.take(2)
}
uversion.toInt()
} }
/** /**
* 判断当前 JDK 版本是否大于 8 * 判断当前 JDK 版本是否大于 8
*
* @return 如果JDK版本大于8返回true,否则返回false
*/ */
val isJdk8Plus: Boolean by lazy { val isJdk8Plus: Boolean by lazy {
javaVersionAsInteger > 8 javaVersionAsInteger > 8
} }
/** /**
* 本地IP地址数组,延迟初始化 * 本地 IPv4 地址数组,跳过回环、虚拟与未启用网卡
* *
* @throws RuntimeException 当获取网络接口信息失败时抛出 * @throws RuntimeException 网络接口枚举失败时抛出
*/ */
val localIps: Array<String> by lazy { val localIps: Array<String> by lazy {
try { try {
val ipList: MutableList<String> = ArrayList() activeNetworkInterfaces()
val interfaces = NetworkInterface.getNetworkInterfaces() .flatMap { it.inetAddresses.toList() }
.filterIsInstance<Inet4Address>()
while (interfaces.hasMoreElements()) { .mapNotNull { it.hostAddress }
val networkInterface = interfaces.nextElement() .toList()
// 跳过回环接口和虚拟接口 .toTypedArray()
if (networkInterface.isLoopback || networkInterface.isVirtual || !networkInterface.isUp) {
continue
}
val addresses = networkInterface.inetAddresses
while (addresses.hasMoreElements()) {
val address = addresses.nextElement()
// 只获取IPv4地址
if (address is Inet4Address) {
ipList.add(address.hostAddress)
}
}
}
ipList.toTypedArray()
} catch (e: SocketException) { } catch (e: SocketException) {
throw RuntimeException("Failed to get local IP addresses", e) throw RuntimeException("Failed to get local IP addresses", e)
} }
} }
/** /**
* 本地IP地址列表,延迟初始化 * 本地 IPv4 地址列表
*/ */
val localIpsByList: List<String> by lazy { val localIpsByList: List<String> by lazy { localIps.toList() }
localIps.toList()
}
/** /**
* 本地回环地址数组,延迟初始化 * 本地回环地址数组;枚举失败时至少包含 `127.0.0.1`
*/ */
val loopbackIps: Array<String> by lazy { val loopbackIps: Array<String> by lazy {
val strings: MutableList<String> = ArrayList(3) try {
return@lazy try { NetworkInterface.getNetworkInterfaces().toList()
val interfaces = NetworkInterface.getNetworkInterfaces() .asSequence()
.filter { it.isLoopback && it.isUp }
while (interfaces.hasMoreElements()) { .flatMap { it.inetAddresses.toList().asSequence() }
val networkInterface = interfaces.nextElement() .mapNotNull { it.hostAddress }
.toList()
// 只处理回环接口 .toTypedArray()
if (networkInterface.isLoopback && networkInterface.isUp) { } catch (_: SocketException) {
val addresses = networkInterface.inetAddresses
while (addresses.hasMoreElements()) {
val address = addresses.nextElement()
strings.add(address.hostAddress)
}
}
}
strings.toTypedArray()
} catch (e: SocketException) {
arrayOf("127.0.0.1") arrayOf("127.0.0.1")
} }
} }
/** /**
* 本地回环地址IP列表,延迟初始化 * 本地回环地址列表
*/ */
val loopbackIpsByList: List<String> by lazy { val loopbackIpsByList: List<String> by lazy { loopbackIps.toList() }
loopbackIps.toList()
}
/** /**
* 获取当前进程的PID * 当前进程 PID;获取失败返回 -1
*
* @return 进程ID,如果无法获取则返回-1
*/ */
val getPid: Long by lazy { val getPid: Long by lazy {
try { runCatching { ProcessHandle.current().pid() }.getOrElse { -1L }
val name = ManagementFactory.getRuntimeMXBean().name
val index = name.indexOf('@')
if (index > 0) {
name.take(index).toLong()
} else {
-1L
}
} catch (e: Exception) {
-1L
}
} }
/** /**
* 获取当前进程的PID字符串形式 * 当前进程 PID 字符串;获取失败返回 "-1"
*
* @return 进程ID字符串,如果无法获取则返回"-1"
*/ */
val pidAsString: String by lazy { val pidAsString: String by lazy {
try { val pid = getPid
val name = ManagementFactory.getRuntimeMXBean().name if (pid == -1L) "-1" else pid.toString()
val index = name.indexOf('@')
if (index > 0) {
name.take(index)
} else {
"-1"
}
} catch (e: Exception) {
"-1"
}
} }
/** /**
* 获取计算机名 * 计算机名;获取失败返回 "unknown"
*
* @return 计算机名,如果无法获取则返回"unknown"
*/ */
val computerName: String by lazy { val computerName: String by lazy {
try { getEnvVar("COMPUTERNAME")
var name = System.getenv("COMPUTERNAME") ?: getEnvVar("HOSTNAME")
if (name.isNullOrBlank()) { ?: runCatching { InetAddress.getLocalHost().hostName }.getOrNull()?.takeIf { it.isNotBlank() }
name = System.getenv("HOSTNAME") ?: "unknown"
}
if (name.isNullOrBlank()) {
name = InetAddress.getLocalHost().hostName
}
name ?: "unknown"
} catch (e: Exception) {
"unknown"
}
} }
/** /**
* 获取当前用户名 * 当前用户名;获取失败返回 "unknown"
*
* @return 当前用户名,如果无法获取则返回"unknown"
*/ */
val userName: String by lazy { val userName: String by lazy {
try { getEnvVar("USERNAME")
getEnvVar("USERNAME") ?: getEnvVar("USER") ?: System.getProperty("user.name") ?: "unknown" ?: getEnvVar("USER")
} catch (e: SecurityException) { ?: runCatching { System.getProperty("user.name") }.getOrNull()?.takeIf { it.isNotBlank() }
"unknown" ?: "unknown"
} catch (e: Exception) {
"unknown"
}
} }
private fun getEnvVar(name: String): String? { private fun getEnvVar(name: String): String? = runCatching {
return try {
System.getenv(name)?.takeIf { it.isNotBlank() } System.getenv(name)?.takeIf { it.isNotBlank() }
} catch (e: SecurityException) { }.getOrNull()
null
}
}
/** /**
* 获取本机MAC地址的字节数组形式 * 本机 MAC 地址字节数组
* *
* @return MAC地址字节数组,如果无法获取则返回空数组 * 未找到可用网卡时回退为 6 字节随机数,避免下游拿到空数组导致错误。
*/ */
val macAddressBytes: ByteArray by lazy { val macAddressBytes: ByteArray by lazy {
try { val found = try {
val interfaces = NetworkInterface.getNetworkInterfaces() activeNetworkInterfaces()
.mapNotNull { runCatching { it.hardwareAddress }.getOrNull() }
while (interfaces.hasMoreElements()) { .firstOrNull { it.isNotEmpty() }
val networkInterface = interfaces.nextElement() } catch (_: SocketException) {
null
// 跳过回环接口和虚拟接口
if (networkInterface.isLoopback || networkInterface.isVirtual || !networkInterface.isUp) {
continue
}
val mac = networkInterface.hardwareAddress
if (mac != null && mac.isNotEmpty()) {
return@lazy mac
}
}
randomByte(6)
} catch (e: SocketException) {
randomByte(6)
} catch (e: Exception) {
randomByte(6)
} }
found ?: randomByte(6)
} }
/** /**
* 获取本机MAC地址的十六进制字符串列表形式 * 本机 MAC 地址的十六进制字符串列表(大写)
*
* @return MAC地址字符串列表,每个元素表示一个字节的十六进制值(大写),如果无法获取则返回空列表
*/ */
val macAddressStringList: List<String> by lazy { val macAddressStringList: List<String> by lazy {
val macBytes = macAddressBytes macAddressBytes.map { HEX_UPPER[it.toInt() and 0xFF] }
if (macBytes.isEmpty()) {
return@lazy emptyList()
}
macBytes.map { String.format("%02X", it) }
} }
/** /**
* 获取本机MAC地址的格式化字符串形式(如 "00:11:22:33:44:55") * 本机 MAC 地址的格式化字符串,如 `00:11:22:33:44:55`
*
* @return 格式化的MAC地址字符串,如果无法获取则返回空字符串
*/ */
val macAddressFormattedString: String by lazy { val macAddressFormattedString: String by lazy {
val macBytes = macAddressBytes macAddressBytes.joinToString(":") { HEX_UPPER[it.toInt() and 0xFF] }
if (macBytes.isEmpty()) {
return@lazy ""
}
macBytes.joinToString(":") { String.format("%02X", it) }
} }
/** /**
* 获取所有网络接口的MAC地址映射 * 所有非回环、非虚拟网卡的 MAC 地址映射,key 为网卡名
*
* @return Map结构,key为网络接口名称,value为对应的MAC地址字节数组
*/ */
val allMacAddresses: Map<String, ByteArray> by lazy { val allMacAddresses: Map<String, ByteArray> by lazy {
try { try {
val result = mutableMapOf<String, ByteArray>() NetworkInterface.getNetworkInterfaces().toList()
val interfaces = NetworkInterface.getNetworkInterfaces() .asSequence()
.filter { !it.isLoopback && !it.isVirtual }
while (interfaces.hasMoreElements()) { .mapNotNull { ni ->
val networkInterface = interfaces.nextElement() val mac = runCatching { ni.hardwareAddress }.getOrNull()
if (mac != null && mac.isNotEmpty()) ni.name to mac else null
// 跳过回环接口和虚拟接口
if (networkInterface.isLoopback || networkInterface.isVirtual) {
continue
} }
.toMap()
val mac = networkInterface.hardwareAddress } catch (_: SocketException) {
if (mac != null && mac.isNotEmpty()) {
result[networkInterface.name] = mac
}
}
result
} catch (e: SocketException) {
emptyMap()
} catch (e: Exception) {
emptyMap() emptyMap()
} }
} }
/** /**
* 获取所有网络接口的MAC地址字符串列表映射 * 所有网卡 MAC 地址的十六进制字符串列表映射
*
* @return Map结构,key为网络接口名称,value为对应的MAC地址字符串列表
*/ */
val allMacAddressesStringList: Map<String, List<String>> by lazy { val allMacAddressesStringList: Map<String, List<String>> by lazy {
allMacAddresses.mapValues { entry -> allMacAddresses.mapValues { (_, bytes) -> bytes.map { HEX_UPPER[it.toInt() and 0xFF] } }
entry.value.map { String.format("%02X", it) }
}
} }
/** /**
* 获取可用处理器数量的懒加载属性 * 可用处理器数量
*/ */
val availableProcessors: Int by lazy { val availableProcessors: Int by lazy {
Runtime.getRuntime().availableProcessors() Runtime.getRuntime().availableProcessors()
} }
private fun activeNetworkInterfaces(): Sequence<NetworkInterface> =
private var isLoadprotocol = false NetworkInterface.getNetworkInterfaces().toList().asSequence()
private var protocol = "" .filter { !it.isLoopback && !it.isVirtual && it.isUp }
/** private val protocol: String by lazy {
* 判断是否为开发模式(file协议) val target = ProtocolAnchor::class.java
*/ val resourceName = target.simpleName + ".class"
val isDevMode: Boolean by lazy { val resource: URL = target.getResource(resourceName)
protocol == "file" ?: throw IllegalStateException(
} "Unable to locate resource '$resourceName' for class ${target.name}"
/**
* 判断是否不为开发模式
*/
val isNotDevMode: Boolean by lazy {
protocol != "file"
}
/**
* 判断是否为JAR模式
*/
val isJarMode: Boolean by lazy {
protocol == "jar"
}
/**
* 判断是否不为JAR模式
*/
val isNotJarMode: Boolean by lazy {
protocol != "jar"
}
/**
* 判断是否为WAR模式
*/
val isWarMode: Boolean by lazy {
protocol == "war"
}
/**
* 判断是否不为WAR模式
*/
val isNotMode: Boolean by lazy {
protocol != "war"
}
/**
* 判断是否为JSWAR模式
*/
val isJswarMode: Boolean by lazy {
protocol == "jswar"
}
/**
* 判断是否不为JSWAR模式
*/
val isNotJswarMode: Boolean by lazy {
protocol != "jswar"
}
/**
* 加载并获取资源协议
* @param clazz 要获取协议的类对象,默认为null
* @return 返回资源的协议字符串
*/
fun loadProtocol(clazz: Class<*>? = null): String {
// 如果已经加载过协议且clazz为null,则直接返回已缓存的协议
if (isLoadprotocol && clazz == null) {
return protocol
}
val resource: URL? = clazz!!.getResource(
clazz.getSimpleName() + ".class"
) )
protocol = resource!!.protocol resource.protocol
return protocol.let {
isLoadprotocol = true
it
}
} }
/** 是否为开发模式(file 协议) */
val isDevMode: Boolean get() = protocol == "file"
/** 是否不为开发模式 */
val isNotDevMode: Boolean get() = protocol != "file"
/** 是否为 JAR 模式 */
val isJarMode: Boolean get() = protocol == "jar"
/** 是否不为 JAR 模式 */
val isNotJarMode: Boolean get() = protocol != "jar"
/** 是否为 WAR 模式 */
val isWarMode: Boolean get() = protocol == "war"
/** 是否不为 WAR 模式 */
val isNotWarMode: Boolean get() = protocol != "war"
/** 是否为 JSWAR 模式 */
val isJswarMode: Boolean get() = protocol == "jswar"
/** 是否不为 JSWAR 模式 */
val isNotJswarMode: Boolean get() = protocol != "jswar"
private object ProtocolAnchor
@@ -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.CountDownLatch
import java.util.concurrent.TimeUnit 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) private var latch = CountDownLatch(1)
@@ -94,6 +100,16 @@ open class ThreadEvent<T> {
return data 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) return latch.await(timeout, unit)
} }
/**
* 事件是否已被设置(自上次 [reset] 以来)
*/
fun isSet(): Boolean = latch.count == 0L
fun setAndReset(data: T) { fun setAndReset(data: T) {
set(data) set(data)
reset() 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) { set(s) {
Thread.currentThread().name = 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)
}
}