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 表达式(去掉多余的 <*>)
This commit is contained in:
2026-10-12 13:57:14 +08:00
parent f7abd6c271
commit 2c423c4aff
9 changed files with 562 additions and 82 deletions
+2 -2
View File
@@ -16,10 +16,10 @@
# ProjectName mingli-utils
# ModuleName mingli-utils
# CurrentFile gradle.properties
# LastUpdate 2026-10-11 16:28:05
# LastUpdate 2026-10-12 13:57:03
# UpdateUser MingLiPro
#
JDKVERSIONS=17
GROUPSID=com.mingliqiye.utils
ARTIFACTID=mingli-utils
VERSIONS=5.3.1
VERSIONS=5.3.2
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Jackson3JsonApi.kt
* LastUpdate 2026-06-21 10:40:58
* LastUpdate 2026-10-12 13:57:11
* UpdateUser MingLiPro
*/
@@ -64,6 +64,9 @@ class Jackson3JsonApi : JsonApi {
_prObjectMapper = ObjectMapper()
}
fun getObjectMapper() = _prObjectMapper
override fun <T> parse(json: String, clazz: Class<T>): T {
try {
return objectMapper.readValue(json, clazz)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JacksonJsonApi.kt
* LastUpdate 2026-10-11 16:54:15
* LastUpdate 2026-10-12 10:48:31
* UpdateUser MingLiPro
*/
@@ -51,6 +51,8 @@ class JacksonJsonApi : JsonApi {
this.objectMapper = ObjectMapper()
}
fun getObjectMapper() = objectMapper
/**
* 使用指定的ObjectMapper构造实例
*
@@ -16,18 +16,18 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile MingliUtilsMetaData.kt
* LastUpdate 2026-03-11 08:46:40
* LastUpdate 2026-10-12 13:32:30
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.metadata
class MingliUtilsMetaData {
var buildTime: String = ""
var groupId: String = ""
var artifactId: String = ""
var version: String = ""
var buildJdkVersion: String = ""
var author: String = ""
var website: String = ""
}
data class MingliUtilsMetaData(
var buildTime: String = "",
var groupId: String = "",
var artifactId: String = "",
var version: String = "",
var buildJdkVersion: String = "",
var author: String = "",
var website: String = "",
)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseMapperQuery.kt
* LastUpdate 2026-02-06 13:15:11
* LastUpdate 2026-10-12 13:33:03
* UpdateUser MingLiPro
*/
@@ -36,7 +36,7 @@ import com.baomidou.mybatisplus.extension.kotlin.KtUpdateWrapper
@Deprecated(
"rename to FastBaseMapper",
replaceWith = ReplaceWith(
expression = "FastBaseMapper<*>",
expression = "FastBaseMapper",
imports = ["com.mingliqiye.utils.mybatisplus.FastBaseMapper"]
),
level = DeprecationLevel.WARNING
@@ -16,129 +16,192 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ObjectPool.kt
* LastUpdate 2026-10-02 16:19:05
* LastUpdate 2026-10-12 13:57:11
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.pool
import com.mingliqiye.utils.require.Require.require
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.locks.Condition
import java.util.concurrent.locks.ReentrantLock
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>(
private val maxSize: Int = Int.MAX_VALUE,
private val minSize: Int = 0,
private val initialSize: Int = 1,
) : Pool<T> {
/**
* 已创建(含空闲与借出)对象的总数,用于容量控制。
* 所有读写均在 [lock] 内完成,保证与 [borrowedCount]、[pool] 一致。
*/
private var createdCount: Int = 0
private val initialCount = AtomicInteger(0)
private val pool = ConcurrentLinkedQueue<ObjectPoolData<T>>()
/** 当前已借出、尚未归还的对象数量([lock] 保护) */
private var borrowedCount: Int = 0
/**
* 空闲对象队列。全部访问均在 [lock] 内完成,
* 因此 [ArrayDeque.size] 即为精确空闲数。
*/
private val pool = ArrayDeque<ObjectPoolData<T>>()
/** 池是否已关闭 */
private val isClosed = AtomicBoolean(false)
private val lock = ReentrantLock()
private val notEmpty: Condition = lock.newCondition()
private val notFull: Condition = lock.newCondition()
init {
require(maxSize >= minSize)
require(initialSize >= minSize)
require(initialSize <= maxSize)
require(maxSize > 0)
repeat(initialSize) {
pool.add(init(initialCount.getAndIncrement()))
pool.addLast(init(createdCount++))
}
}
/**
* 关闭对象池:销毁所有空闲对象,唤醒所有等待者。
* 已借出的对象在归还时会被直接销毁。
*/
override fun close() {
for (poolData in pool) {
destroy(poolData)
lock.withLock {
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> {
lock.withLock {
if (isClosed.get()) {
throw IllegalStateException("Object pool closed")
}
pool.poll()?.let { return it }
if (initialCount.get() < maxSize) {
return init(initialCount.getAndIncrement())
}
var remainingNanos = if (timeoutMillis > 0) TimeUnit.MILLISECONDS.toNanos(timeoutMillis) else -1L
// 3. 池已满且无空闲,等待归还
if (timeoutMillis <= 0) {
// 无限等待
while (pool.isEmpty()) {
notEmpty.await() // 释放锁并等待
while (true) {
if (isClosed.get()) {
throw IllegalStateException("Object pool closed")
}
return pool.poll()
}
// 有限时间等待
var remainingNanos = TimeUnit.MILLISECONDS.toNanos(timeoutMillis)
while (pool.isEmpty()) {
if (remainingNanos <= 0) {
// 1. 优先取空闲对象
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. 池已满且无空闲,等待归还
if (remainingNanos < 0) {
notEmpty.await()
} else if (remainingNanos == 0L) {
throw IllegalStateException("Timeout waiting for object from pool")
} else {
remainingNanos = notEmpty.awaitNanos(remainingNanos)
if (remainingNanos <= 0L) {
throw IllegalStateException("Timeout waiting for object from pool")
}
}
remainingNanos = notEmpty.awaitNanos(remainingNanos)
}
return pool.poll()
}
}
/**
* 归还对象到池中。
* 若池已关闭或对象不属于当前池,则直接销毁;否则回填到空闲队列并唤醒等待者。
*/
override fun returnObject(obj: ObjectPoolData<T>) {
lock.withLock {
if (isClosed.get()) {
throw InterruptedException("Object pool closed")
borrowedCount--
if (isClosed.get() || obj.objectPool !== this) {
runCatching { destroy(obj) }
createdCount--
notFull.signal()
return
}
pool.add(obj)
pool.addLast(obj)
notEmpty.signal()
}
}
}
/**
* 当前空闲对象数量(精确值)。
* 通过短暂持锁读取,与 [activeSize]/[totalSize] 各自独立但均为调用瞬间的真实值。
*/
fun idleSize(): Int = lock.withLock { pool.size }
/** 当前已借出、尚未归还的对象数量(精确值) */
fun activeSize(): Int = lock.withLock { borrowedCount }
interface Pool<T> {
fun close()
fun borrow(timeoutMillis: Long): ObjectPoolData<T>
fun borrow(): ObjectPoolData<T> = borrow(0)
fun returnObject(obj: ObjectPoolData<T>)
fun use(funs: (ObjectPoolData<T>) -> Unit) = use(0, funs)
fun init(id: Int): ObjectPoolData<T>
fun destroy(data: ObjectPoolData<T>)
fun use(timeoutMillis: Long, funs: (ObjectPoolData<T>) -> Unit) {
val i = borrow(timeoutMillis)
funs(i)
returnObject(i)
}
}
/** 已创建对象总数,含空闲与借出(精确值) */
fun totalSize(): Int = lock.withLock { createdCount }
data class ObjectPoolData<T>(
val obj: T,
val objectPool: ObjectPool<T>,
val id: Int = obj.hashCode(),
val name: String = "",
)
/** 池是否已关闭 */
fun closed(): Boolean = isClosed.get()
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()
/**
* 一次性读取空闲 / 借出 / 总数 的一致快照(同一把锁内)。
*
* 相比分别调用三个方法,可避免三者之间因并发导致的不自洽
* (例如 `idle + active != total`)。
*/
fun snapshot(): PoolSnapshot = lock.withLock {
PoolSnapshot(idle = pool.size, active = borrowedCount, total = createdCount, closed = isClosed.get())
}
/**
* 池状态快照。
* @property idle 空闲对象数
* @property active 已借出对象数
* @property total 已创建对象总数(= idle + active)
* @property closed 池是否已关闭
*/
data class PoolSnapshot(val idle: Int, val active: Int, val total: Int, val closed: Boolean)
}
@@ -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) }
}
}
}
@@ -0,0 +1,298 @@
/*
* Copyright 2026 mingliqiye
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ThreadPool.kt
* LastUpdate 2026-10-12 13:57:11
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.pool
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicLong
/**
* 可复用线程池。
*
* 与直接管理 [Thread] 的对象池不同,本实现的池对象是一个 [Worker]:
* 每个 Worker 内部持有一个**长期存活**的守护线程和一个任务队列,
* 线程通过 `while` 循环不断消费队列中的任务,从而实现真正意义上的线程复用
* (避免频繁创建/销毁线程带来的开销,并保留线程本地状态)。
*
* ## 使用方式
*
* ```kotlin
* ThreadPool(maxSize = 4, initialSize = 2).use { pool ->
* // 同步执行:借出 Worker -> 执行 -> 归还
* pool.execute { println("task on ${Thread.currentThread().name}") }
*
* // 带返回值
* val result = pool.call(Callable { 1 + 1 })
*
* // 异步提交:任务完成后自动归还 Worker
* val future = pool.submit(Callable { doSomething() })
* future.get()
*
* // 直接借出 Worker 使用
* pool.use { data -> data.obj.execute { /* ... */ } }
* }
* ```
*
* @property maxSize 最大 Worker 数量(同时也是最大并发任务数)
* @property minSize 保留的最小空闲 Worker 数量
* @property initialSize 预热的 Worker 数量
* @property namePrefix Worker 线程名前缀,最终名称为 `${namePrefix}-${id}`
* @property daemon Worker 线程是否为守护线程,默认 true
* @property uncaughtHandler 任务抛出未捕获异常时的处理器
*/
class ThreadPool(
maxSize: Int = Runtime.getRuntime().availableProcessors().coerceAtLeast(2),
minSize: Int = 0,
initialSize: Int = 1,
private val namePrefix: String = "MingLiThreadPool",
private val daemon: Boolean = true,
private val uncaughtHandler: Thread.UncaughtExceptionHandler = Thread.UncaughtExceptionHandler { _, _ -> },
) : ObjectPool<ThreadPool.Worker>(maxSize, minSize, initialSize), AutoCloseable {
/** 已提交任务总数 */
private val submittedTasks = AtomicLong(0)
/** 已完成任务总数 */
private val completedTasks = AtomicLong(0)
/** 已失败任务总数 */
private val failedTasks = AtomicLong(0)
/** 已创建的全部 Worker 引用,用于 [closeAndAwait] 等待线程退出 */
private val allWorkers = CopyOnWriteArrayList<Worker>()
override fun init(id: Int): ObjectPoolData<Worker> {
val worker = Worker(id, namePrefix, daemon, uncaughtHandler)
worker.start()
allWorkers.add(worker)
return ObjectPoolData(
obj = worker,
objectPool = this,
id = id,
name = worker.threadName,
)
}
override fun destroy(data: ObjectPoolData<Worker>) {
data.obj.shutdown()
allWorkers.remove(data.obj)
}
/**
* 同步执行任务:从池借出一个 Worker,在其线程上运行 [task],结束后归还。
* 任务的异常会被封装为 [ExecutionException] 抛出。
*/
@JvmOverloads
fun execute(task: Runnable, timeoutMillis: Long = 0) {
call(Callable { task.run(); null }, timeoutMillis)
}
/**
* 同步执行带返回值的任务。
*/
@JvmOverloads
fun <R> call(task: Callable<R>, timeoutMillis: Long = 0): R {
return useResult(timeoutMillis) { data ->
data.obj.call(task)
}
}
/**
* 异步提交任务,立即返回 [CompletableFuture]。
*
* Worker 会一直被占用直到任务执行完成,然后自动归还给池;
* 因此在 `maxSize` 达到上限时,新的提交会阻塞在 borrow 阶段。
*/
@JvmOverloads
fun <R> submit(task: Callable<R>, timeoutMillis: Long = 0): CompletableFuture<R> {
val data = borrow(timeoutMillis)
submittedTasks.incrementAndGet()
val future = data.obj.submitAsync(task)
return future.whenComplete { _, err ->
if (err != null) failedTasks.incrementAndGet() else completedTasks.incrementAndGet()
runCatching { returnObject(data) }
}
}
/** 异步提交无返回值任务;使用独立方法名避免与 [submit] 的 lambda 重载歧义 */
@JvmOverloads
fun submitRunnable(task: Runnable, timeoutMillis: Long = 0): CompletableFuture<Void?> {
return submit(Callable { task.run(); null as Void? }, timeoutMillis)
}
/** 已提交任务总数 */
fun submittedCount(): Long = submittedTasks.get()
/** 已完成任务总数 */
fun completedCount(): Long = completedTasks.get()
/** 已失败任务总数 */
fun failedCount(): Long = failedTasks.get()
/**
* 池中的工作单元:一个长期存活的守护线程 + 一个任务队列。
*
* 通过 [submit]/[call]/[execute] 向 Worker 投递任务,Worker 线程循环消费执行。
* 只有在池 [close] 时才会调用 [shutdown] 结束该线程。
*/
class Worker internal constructor(
val id: Int,
namePrefix: String,
daemon: Boolean,
private val uncaughtHandler: Thread.UncaughtExceptionHandler,
) {
private val taskQueue = LinkedBlockingQueue<Runnable>()
private val shutdown = AtomicBoolean(false)
private val started = AtomicBoolean(false)
/** Worker 线程名称 */
val threadName: String = "$namePrefix-$id"
/** Worker 线程引用,只读 */
val thread: Thread = Thread({ runLoop() }, threadName).apply {
isDaemon = daemon
}
internal fun start() {
if (started.compareAndSet(false, true)) {
thread.start()
}
}
private fun runLoop() {
while (!shutdown.get() || taskQueue.isNotEmpty()) {
val task = try {
// 使用轮询而非 take(),以便 shutdown 标志能及时生效
taskQueue.poll(100, TimeUnit.MILLISECONDS)
} catch (_: InterruptedException) {
if (shutdown.get()) break else null
}
if (task != null) {
try {
task.run()
} catch (t: Throwable) {
try {
uncaughtHandler.uncaughtException(thread, t)
} catch (_: Throwable) {
// 忽略处理器自身的异常,防止线程意外退出
}
}
}
}
}
/**
* 异步提交任务,返回 Future。任务在该 Worker 线程上执行。
* @throws IllegalStateException 若 Worker 已关闭
*/
fun <R> submitAsync(task: Callable<R>): CompletableFuture<R> {
check(!shutdown.get()) { "Worker[$threadName] already shutdown" }
val future = CompletableFuture<R>()
val wrapper = Runnable {
try {
future.complete(task.call())
} catch (t: Throwable) {
future.completeExceptionally(t)
}
}
if (!taskQueue.offer(wrapper)) {
future.completeExceptionally(IllegalStateException("Worker[$threadName] rejected task"))
}
return future
}
/** 同步执行任务,返回结果 */
fun <R> call(task: Callable<R>): R {
try {
return submitAsync(task).get()
} catch (e: ExecutionException) {
throw e.cause ?: e
}
}
/** 同步执行任务,忽略返回值 */
fun execute(task: Runnable) {
call(Callable { task.run(); null })
}
/** 当前待执行任务数 */
fun pendingTasks(): Int = taskQueue.size
/** Worker 是否已关闭 */
fun isShutdown(): Boolean = shutdown.get()
/** 线程是否存活 */
fun isAlive(): Boolean = thread.isAlive
internal fun shutdown() {
if (shutdown.compareAndSet(false, true)) {
thread.interrupt()
}
}
/** 等待 Worker 线程结束,最多 [timeoutMillis] 毫秒 */
@JvmOverloads
fun awaitTermination(timeoutMillis: Long = 0) {
if (timeoutMillis <= 0) thread.join() else thread.join(timeoutMillis)
}
override fun toString(): String =
"Worker(id=$id, name=$threadName, pending=${taskQueue.size}, alive=${thread.isAlive})"
}
/**
* 关闭池:销毁所有 Worker 线程。
* 由于 Worker 线程默认为守护线程,未调用 [closeAndAwait] 时不会阻塞 JVM 退出。
*/
override fun close() {
super.close()
}
/**
* 关闭池并阻塞等待所有 Worker 线程结束。
* @param timeoutMillis 每个 Worker 最长等待时间
*/
@JvmOverloads
fun closeAndAwait(timeoutMillis: Long = 5_000) {
val snapshot = allWorkers.toList()
super.close()
snapshot.forEach { it.awaitTermination(timeoutMillis) }
}
companion object {
/** 依据 CPU 核数创建默认大小的线程池 */
@JvmStatic
fun defaultPool(): ThreadPool = ThreadPool()
/** 创建固定大小的线程池 */
@JvmStatic
fun fixed(size: Int, namePrefix: String = "MingLiFixedPool"): ThreadPool =
ThreadPool(maxSize = size, minSize = size, initialSize = size, namePrefix = namePrefix)
/** 创建单线程池,保证任务串行执行 */
@JvmStatic
fun single(namePrefix: String = "MingLiSinglePool"): ThreadPool =
ThreadPool(maxSize = 1, minSize = 1, initialSize = 1, namePrefix = namePrefix)
}
}