feat(thread): 新增线程工具集与线程池构建体系
- ThreadPoolBuilder: DSL 风格线程池构建器,含 fixed/single/cached/io/cpu/scheduled 预设 - GlobalThreadPool: 全局 IO/CPU/定时三类共享线程池及便捷提交函数 - ThreadPoolMonitor: 线程池运行快照与周期监控 - ThreadPoolExt: ExecutorService/Future/CompletableFuture 便捷扩展 - AsyncTasks: 并行执行、竞速执行、重试与定时任务编排 - ThreadLocalDelegates: ThreadLocal 属性委托 - ThreadExt: Thread/Runnable 扩展与守护线程便捷创建 - ThreadUtils 增强: 休眠、线程枚举、全线程栈转储 - ThreadEvent 增强: operator invoke、属性委托、isSet 与超时取数 - 移除 pool 包旧 ThreadPool.kt - 新增 5 个测试类共 83 个单元测试
This commit is contained in:
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user