From 474071e43b6d765eb1a713c4d735bcb686b79535 Mon Sep 17 00:00:00 2001 From: minglipro Date: Mon, 19 Oct 2026 21:09:57 +0800 Subject: [PATCH 1/2] =?UTF-8?q?feat(thread):=20=E6=96=B0=E5=A2=9E=E7=BA=BF?= =?UTF-8?q?=E7=A8=8B=E5=B7=A5=E5=85=B7=E9=9B=86=E4=B8=8E=E7=BA=BF=E7=A8=8B?= =?UTF-8?q?=E6=B1=A0=E6=9E=84=E5=BB=BA=E4=BD=93=E7=B3=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 个单元测试 --- .../com/mingliqiye/utils/pool/ThreadPool.kt | 298 ------------------ .../com/mingliqiye/utils/thread/AsyncTasks.kt | 188 +++++++++++ .../utils/thread/GlobalThreadPool.kt | 122 +++++++ .../mingliqiye/utils/thread/ThreadEvent.kt | 54 +++- .../com/mingliqiye/utils/thread/ThreadExt.kt | 164 ++++++++++ .../utils/thread/ThreadLocalDelegates.kt | 75 +++++ .../utils/thread/ThreadPoolBuilder.kt | 234 ++++++++++++++ .../mingliqiye/utils/thread/ThreadPoolExt.kt | 150 +++++++++ .../utils/thread/ThreadPoolMonitor.kt | 124 ++++++++ .../mingliqiye/utils/thread/ThreadUtils.kt | 94 ++++++ .../mingliqiye/utils/thread/AsyncTasksTest.kt | 280 ++++++++++++++++ .../utils/thread/ThreadEventTest.kt | 151 +++++++++ .../utils/thread/ThreadPoolBuilderTest.kt | 213 +++++++++++++ .../utils/thread/ThreadPoolExtTest.kt | 266 ++++++++++++++++ .../utils/thread/ThreadToolsTest.kt | 228 ++++++++++++++ 15 files changed, 2341 insertions(+), 300 deletions(-) delete mode 100644 src/main/kotlin/com/mingliqiye/utils/pool/ThreadPool.kt create mode 100644 src/main/kotlin/com/mingliqiye/utils/thread/AsyncTasks.kt create mode 100644 src/main/kotlin/com/mingliqiye/utils/thread/GlobalThreadPool.kt create mode 100644 src/main/kotlin/com/mingliqiye/utils/thread/ThreadExt.kt create mode 100644 src/main/kotlin/com/mingliqiye/utils/thread/ThreadLocalDelegates.kt create mode 100644 src/main/kotlin/com/mingliqiye/utils/thread/ThreadPoolBuilder.kt create mode 100644 src/main/kotlin/com/mingliqiye/utils/thread/ThreadPoolExt.kt create mode 100644 src/main/kotlin/com/mingliqiye/utils/thread/ThreadPoolMonitor.kt create mode 100644 src/test/kotlin/com/mingliqiye/utils/thread/AsyncTasksTest.kt create mode 100644 src/test/kotlin/com/mingliqiye/utils/thread/ThreadEventTest.kt create mode 100644 src/test/kotlin/com/mingliqiye/utils/thread/ThreadPoolBuilderTest.kt create mode 100644 src/test/kotlin/com/mingliqiye/utils/thread/ThreadPoolExtTest.kt create mode 100644 src/test/kotlin/com/mingliqiye/utils/thread/ThreadToolsTest.kt diff --git a/src/main/kotlin/com/mingliqiye/utils/pool/ThreadPool.kt b/src/main/kotlin/com/mingliqiye/utils/pool/ThreadPool.kt deleted file mode 100644 index 89d9e58..0000000 --- a/src/main/kotlin/com/mingliqiye/utils/pool/ThreadPool.kt +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Copyright 2026 mingliqiye - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * ProjectName mingli-utils - * ModuleName mingli-utils.main - * CurrentFile ThreadPool.kt - * LastUpdate 2026-10-12 13:57:11 - * UpdateUser MingLiPro - */ - -package com.mingliqiye.utils.pool - -import java.util.concurrent.* -import java.util.concurrent.atomic.AtomicBoolean -import java.util.concurrent.atomic.AtomicLong - -/** - * 可复用线程池。 - * - * 与直接管理 [Thread] 的对象池不同,本实现的池对象是一个 [Worker]: - * 每个 Worker 内部持有一个**长期存活**的守护线程和一个任务队列, - * 线程通过 `while` 循环不断消费队列中的任务,从而实现真正意义上的线程复用 - * (避免频繁创建/销毁线程带来的开销,并保留线程本地状态)。 - * - * ## 使用方式 - * - * ```kotlin - * ThreadPool(maxSize = 4, initialSize = 2).use { pool -> - * // 同步执行:借出 Worker -> 执行 -> 归还 - * pool.execute { println("task on ${Thread.currentThread().name}") } - * - * // 带返回值 - * val result = pool.call(Callable { 1 + 1 }) - * - * // 异步提交:任务完成后自动归还 Worker - * val future = pool.submit(Callable { doSomething() }) - * future.get() - * - * // 直接借出 Worker 使用 - * pool.use { data -> data.obj.execute { /* ... */ } } - * } - * ``` - * - * @property maxSize 最大 Worker 数量(同时也是最大并发任务数) - * @property minSize 保留的最小空闲 Worker 数量 - * @property initialSize 预热的 Worker 数量 - * @property namePrefix Worker 线程名前缀,最终名称为 `${namePrefix}-${id}` - * @property daemon Worker 线程是否为守护线程,默认 true - * @property uncaughtHandler 任务抛出未捕获异常时的处理器 - */ -class ThreadPool( - maxSize: Int = Runtime.getRuntime().availableProcessors().coerceAtLeast(2), - minSize: Int = 0, - initialSize: Int = 1, - private val namePrefix: String = "MingLiThreadPool", - private val daemon: Boolean = true, - private val uncaughtHandler: Thread.UncaughtExceptionHandler = Thread.UncaughtExceptionHandler { _, _ -> }, -) : ObjectPool(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() - - override fun init(id: Int): ObjectPoolData { - 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) { - 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 call(task: Callable, timeoutMillis: Long = 0): R { - return useResult(timeoutMillis) { data -> - data.obj.call(task) - } - } - - /** - * 异步提交任务,立即返回 [CompletableFuture]。 - * - * Worker 会一直被占用直到任务执行完成,然后自动归还给池; - * 因此在 `maxSize` 达到上限时,新的提交会阻塞在 borrow 阶段。 - */ - @JvmOverloads - fun submit(task: Callable, timeoutMillis: Long = 0): CompletableFuture { - 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 { - 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() - 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 submitAsync(task: Callable): CompletableFuture { - check(!shutdown.get()) { "Worker[$threadName] already shutdown" } - val future = CompletableFuture() - 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 call(task: Callable): 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) - } -} diff --git a/src/main/kotlin/com/mingliqiye/utils/thread/AsyncTasks.kt b/src/main/kotlin/com/mingliqiye/utils/thread/AsyncTasks.kt new file mode 100644 index 0000000..65e3e52 --- /dev/null +++ b/src/main/kotlin/com/mingliqiye/utils/thread/AsyncTasks.kt @@ -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 runParallel( + vararg tasks: () -> T, + executor: ExecutorService = GlobalThreadPool.io, +): List = executor.invokeAllAndGet(tasks.map { Callable(it) }) + +/** + * 并行执行全部任务,阻塞等待所有完成,按输入顺序返回结果 + */ +fun runParallel( + tasks: Collection<() -> T>, + executor: ExecutorService = GlobalThreadPool.io, +): List = executor.invokeAllAndGet(tasks.map { Callable(it) }) + +/** + * 并行执行全部任务,任一任务在超时时间内未完成则抛出 [java.util.concurrent.TimeoutException] + */ +fun runParallelWithin( + timeout: Long, + unit: TimeUnit = TimeUnit.MILLISECONDS, + executor: ExecutorService = GlobalThreadPool.io, + tasks: Collection<() -> T>, +): List { + 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 firstCompleted( + vararg tasks: () -> T, + executor: ExecutorService = GlobalThreadPool.io, +): T = executor.invokeAny(tasks.map { Callable(it) }) + +/** + * 执行全部任务,返回第一个成功完成的任务结果,其余任务取消 + */ +fun firstCompleted( + tasks: Collection<() -> T>, + executor: ExecutorService = GlobalThreadPool.io, +): T = executor.invokeAny(tasks.map { Callable(it) }) + +// ---- 集合工具 ---- + +/** + * 等待所有 Future 完成并按顺序收集结果,任一失败抛出原始异常 + */ +fun awaitAll(futures: Collection>): List = futures.map { it.await() } + +/** + * 提交全部 Callable 并阻塞等待所有完成,任一失败抛出原始异常 + */ +fun ExecutorService.invokeAllAndGet(tasks: Collection>): List = + invokeAll(tasks).map { it.await() } + +/** + * 等待所有 Future 完成,失败的任务返回 null(不中断整体流程) + */ +fun awaitAllOrNull(futures: Collection>): List = + futures.map { it.getOrNull() } + +// ---- 重试 ---- + +/** + * 带重试的调用:任务抛出异常时重试,全部失败抛出最后一次异常。 + * + * ```kotlin + * val data = callWithRetry(3, delayMillis = 500) { httpGet(url) } + * ``` + * + * @param times 总尝试次数(含首次),必须 >= 1 + * @param delayMillis 每次重试前的等待毫秒数 + */ +fun 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 callAsyncWithRetry( + times: Int, + delayMillis: Long = 0, + task: () -> T, +): Future = 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) diff --git a/src/main/kotlin/com/mingliqiye/utils/thread/GlobalThreadPool.kt b/src/main/kotlin/com/mingliqiye/utils/thread/GlobalThreadPool.kt new file mode 100644 index 0000000..72ead19 --- /dev/null +++ b/src/main/kotlin/com/mingliqiye/utils/thread/GlobalThreadPool.kt @@ -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 submit(callable: Callable): Future = io.submit(callable) + + @JvmStatic + fun submit(runnable: Runnable): Future<*> = io.submit(runnable) + + @JvmStatic + fun submit(runnable: Runnable, result: T): Future = 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 callAsync(block: () -> T): Future = GlobalThreadPool.io.submit(Callable(block)) + +/** + * 向全局 CPU 池提交计算任务 + */ +fun computeAsync(block: () -> T): Future = GlobalThreadPool.cpu.submit(Callable(block)) + +/** + * 在全局 IO 池执行任务并阻塞等待完成 + */ +fun runAsyncAwait(block: () -> Unit) { + GlobalThreadPool.io.submit(block).get() +} + +/** + * 在全局 IO 池执行任务并阻塞等待结果 + */ +fun callAsyncAwait(block: () -> T): T = GlobalThreadPool.io.submit(Callable(block)).get() diff --git a/src/main/kotlin/com/mingliqiye/utils/thread/ThreadEvent.kt b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadEvent.kt index 9c14cef..8edeebb 100644 --- a/src/main/kotlin/com/mingliqiye/utils/thread/ThreadEvent.kt +++ b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadEvent.kt @@ -24,11 +24,17 @@ package com.mingliqiye.utils.thread import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit +import kotlin.properties.ReadWriteProperty +import kotlin.reflect.KProperty /** - * 线程事件同步工具类,用于线程间的事件通知和等待 + * 线程事件同步工具类,用于线程间的事件通知和等待。 + * + * 支持 Kotlin 便捷语法: + * - `event()` 读取数据,`event(newData)` 设置数据并唤醒等待线程 + * - `val value by event` 直接作为属性委托使用 */ -open class ThreadEvent { +open class ThreadEvent : ReadWriteProperty { private var latch = CountDownLatch(1) @@ -94,6 +100,16 @@ open class ThreadEvent { 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 { return latch.await(timeout, unit) } + /** + * 事件是否已被设置(自上次 [reset] 以来) + */ + fun isSet(): Boolean = latch.count == 0L + fun setAndReset(data: T) { set(data) reset() } + + // ---- Kotlin 便捷语法 ---- + + /** 读取事件数据:`val d = event()` */ + operator fun invoke(): T = data + + /** 设置事件数据并唤醒等待线程:`event(newData)` */ + operator fun invoke(data: T) = set(data) + + /** 支持属性委托:`var value by event` */ + override operator fun getValue(thisRef: Any?, property: KProperty<*>): T = data + + /** 支持属性委托:`value = newData` 等价于 [set] */ + override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = set(value) + + /** + * 以自身为委托,返回属性委托视图 + */ + fun asDelegate(): ReadWriteProperty = this + + companion object { + /** + * 创建事件实例 + * + * @param data 初始数据 + */ + @JvmStatic + fun of(data: T): ThreadEvent = ThreadEvent(data) + } } diff --git a/src/main/kotlin/com/mingliqiye/utils/thread/ThreadExt.kt b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadExt.kt new file mode 100644 index 0000000..a8aa26a --- /dev/null +++ b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadExt.kt @@ -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() diff --git a/src/main/kotlin/com/mingliqiye/utils/thread/ThreadLocalDelegates.kt b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadLocalDelegates.kt new file mode 100644 index 0000000..64455be --- /dev/null +++ b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadLocalDelegates.kt @@ -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( + private val threadLocal: ThreadLocal, +) : ReadWriteProperty { + + 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 threadLocal(initial: () -> T): ThreadLocalDelegate = + ThreadLocalDelegate(ThreadLocal.withInitial(Supplier(initial))) + +/** + * 创建无初始值的线程局部属性委托,属性类型需声明为可空: + * + * ```kotlin + * var value: String? by nullableThreadLocal() + * ``` + */ +fun nullableThreadLocal(): ThreadLocalDelegate = + ThreadLocalDelegate(ThreadLocal()) + +/** + * 将已有 [ThreadLocal] 实例包装为属性委托 + */ +fun ThreadLocal.asDelegate(): ThreadLocalDelegate = ThreadLocalDelegate(this) diff --git a/src/main/kotlin/com/mingliqiye/utils/thread/ThreadPoolBuilder.kt b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadPoolBuilder.kt new file mode 100644 index 0000000..cb96154 --- /dev/null +++ b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadPoolBuilder.kt @@ -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 = 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)) diff --git a/src/main/kotlin/com/mingliqiye/utils/thread/ThreadPoolExt.kt b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadPoolExt.kt new file mode 100644 index 0000000..02218fc --- /dev/null +++ b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadPoolExt.kt @@ -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 Future.await(): T = try { + get() +} catch (e: ExecutionException) { + throw e.cause ?: e +} + +/** + * 阻塞等待任务完成,返回结果;超时或执行失败返回 null。 + */ +fun Future.getOrNull( + timeout: Long = Long.MAX_VALUE, + unit: TimeUnit = TimeUnit.MILLISECONDS, +): T? = try { + get(timeout, unit) +} catch (_: Exception) { + null +} + +/** + * 阻塞等待任务完成,失败或超时返回默认值。 + */ +fun Future.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 Future.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 completableFuture( + executor: Executor? = null, + block: () -> T, +): CompletableFuture = if (executor == null) { + CompletableFuture.supplyAsync(Supplier(block)) +} else { + CompletableFuture.supplyAsync(Supplier(block), executor) +} + +/** + * 在指定线程池创建无返回值 [CompletableFuture] + */ +fun runCompletableFuture( + executor: Executor? = null, + block: () -> Unit, +): CompletableFuture = if (executor == null) { + CompletableFuture.runAsync(block) +} else { + CompletableFuture.runAsync(block, executor) +} diff --git a/src/main/kotlin/com/mingliqiye/utils/thread/ThreadPoolMonitor.kt b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadPoolMonitor.kt new file mode 100644 index 0000000..737e929 --- /dev/null +++ b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadPoolMonitor.kt @@ -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() diff --git a/src/main/kotlin/com/mingliqiye/utils/thread/ThreadUtils.kt b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadUtils.kt index 79a1204..47fdcc0 100644 --- a/src/main/kotlin/com/mingliqiye/utils/thread/ThreadUtils.kt +++ b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadUtils.kt @@ -40,4 +40,98 @@ object ThreadUtils { set(s) { Thread.currentThread().name = s } + + /** + * 当前线程的优先级 + */ + @get:JvmStatic + val currentThreadPriority: Int + get() = Thread.currentThread().priority + + /** + * 当前线程是否为守护线程 + */ + @JvmStatic + fun isCurrentDaemon(): Boolean = Thread.currentThread().isDaemon + + /** + * 当前线程是否为主线程 + */ + @JvmStatic + fun isMainThread(): Boolean = Thread.currentThread().name == "main" + + /** + * 当前线程的调用栈 + */ + @JvmStatic + fun currentStackTrace(): Array = Thread.currentThread().stackTrace + + /** + * 当前线程组 + */ + @JvmStatic + fun currentThreadGroup(): ThreadGroup = Thread.currentThread().threadGroup + + /** + * 当前线程组中活跃线程的估算数量 + */ + @JvmStatic + fun activeThreadCount(): Int = Thread.activeCount() + + /** + * 枚举当前线程组中所有活跃线程 + */ + @JvmStatic + fun activeThreads(): Array { + val all = arrayOfNulls(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") + } + } } diff --git a/src/test/kotlin/com/mingliqiye/utils/thread/AsyncTasksTest.kt b/src/test/kotlin/com/mingliqiye/utils/thread/AsyncTasksTest.kt new file mode 100644 index 0000000..4207917 --- /dev/null +++ b/src/test/kotlin/com/mingliqiye/utils/thread/AsyncTasksTest.kt @@ -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> = listOf( + pool.submit(Callable { 1 }), + pool.submit(Callable { 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)) + } +} diff --git a/src/test/kotlin/com/mingliqiye/utils/thread/ThreadEventTest.kt b/src/test/kotlin/com/mingliqiye/utils/thread/ThreadEventTest.kt new file mode 100644 index 0000000..f700967 --- /dev/null +++ b/src/test/kotlin/com/mingliqiye/utils/thread/ThreadEventTest.kt @@ -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()) + } +} diff --git a/src/test/kotlin/com/mingliqiye/utils/thread/ThreadPoolBuilderTest.kt b/src/test/kotlin/com/mingliqiye/utils/thread/ThreadPoolBuilderTest.kt new file mode 100644 index 0000000..6138f4c --- /dev/null +++ b/src/test/kotlin/com/mingliqiye/utils/thread/ThreadPoolBuilderTest.kt @@ -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() + } + } +} diff --git a/src/test/kotlin/com/mingliqiye/utils/thread/ThreadPoolExtTest.kt b/src/test/kotlin/com/mingliqiye/utils/thread/ThreadPoolExtTest.kt new file mode 100644 index 0000000..be97ab2 --- /dev/null +++ b/src/test/kotlin/com/mingliqiye/utils/thread/ThreadPoolExtTest.kt @@ -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 = + pool.submit(Callable { 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() + } + } +} diff --git a/src/test/kotlin/com/mingliqiye/utils/thread/ThreadToolsTest.kt b/src/test/kotlin/com/mingliqiye/utils/thread/ThreadToolsTest.kt new file mode 100644 index 0000000..1240344 --- /dev/null +++ b/src/test/kotlin/com/mingliqiye/utils/thread/ThreadToolsTest.kt @@ -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().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() + 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() + // 主线程先设置自己的值 + 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) + } +} From 31987b9b148e0812bb31626c6c057d3807eca0b0 Mon Sep 17 00:00:00 2001 From: minglipro Date: Tue, 20 Oct 2026 20:05:40 +0800 Subject: [PATCH 2/2] a --- .../com/mingliqiye/utils/netty/NettyUtils.kt | 4 +- .../com/mingliqiye/utils/path/OsPath.kt | 42 +- .../random/{RandomBytes.kt => Random.kt} | 7 +- .../com/mingliqiye/utils/require/Require.kt | 229 --- .../mingliqiye/utils/require/RequireTrue.kt | 190 +++ .../com/mingliqiye/utils/require/Required.kt | 23 + .../mingliqiye/utils/stream/SuperStream.java | 1236 +++++++++++++++++ .../utils/stream/SuprtStreamUtils.kt | 0 .../com/mingliqiye/utils/system/SystemUtil.kt | 423 ++---- 9 files changed, 1618 insertions(+), 536 deletions(-) rename src/main/kotlin/com/mingliqiye/utils/random/{RandomBytes.kt => Random.kt} (99%) delete mode 100644 src/main/kotlin/com/mingliqiye/utils/require/Require.kt create mode 100644 src/main/kotlin/com/mingliqiye/utils/require/RequireTrue.kt create mode 100644 src/main/kotlin/com/mingliqiye/utils/require/Required.kt create mode 100644 src/main/kotlin/com/mingliqiye/utils/stream/SuperStream.java rename src/main/{java => kotlin}/com/mingliqiye/utils/stream/SuprtStreamUtils.kt (100%) diff --git a/src/main/kotlin/com/mingliqiye/utils/netty/NettyUtils.kt b/src/main/kotlin/com/mingliqiye/utils/netty/NettyUtils.kt index c2d25ab..8b27c30 100644 --- a/src/main/kotlin/com/mingliqiye/utils/netty/NettyUtils.kt +++ b/src/main/kotlin/com/mingliqiye/utils/netty/NettyUtils.kt @@ -16,7 +16,7 @@ * ProjectName mingli-utils * ModuleName mingli-utils.main * CurrentFile NettyUtils.kt - * LastUpdate 2026-06-27 21:40:00 + * LastUpdate 2026-10-20 20:05:37 * UpdateUser MingLiPro */ @@ -323,7 +323,7 @@ fun ByteBuf.releaseSafely(): Boolean { */ fun ByteBuf.tryRelease(): Boolean { return try { - if (refCnt() > 0) release() else false + refCnt() > 0 && release() } catch (e: Exception) { false } diff --git a/src/main/kotlin/com/mingliqiye/utils/path/OsPath.kt b/src/main/kotlin/com/mingliqiye/utils/path/OsPath.kt index 4e9dc63..8a731fc 100644 --- a/src/main/kotlin/com/mingliqiye/utils/path/OsPath.kt +++ b/src/main/kotlin/com/mingliqiye/utils/path/OsPath.kt @@ -1,5 +1,5 @@ /* - * Copyright 2025 mingliqiye + * 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. @@ -16,7 +16,7 @@ * ProjectName mingli-utils * ModuleName mingli-utils.main * CurrentFile OsPath.kt - * LastUpdate 2025-09-18 09:47:43 + * LastUpdate 2026-10-20 20:05:37 * UpdateUser MingLiPro */ @@ -26,8 +26,7 @@ package com.mingliqiye.utils.path import java.io.File import java.net.URI -import java.nio.file.Path -import java.nio.file.Paths +import java.nio.file.* import java.util.* import java.util.function.Consumer @@ -40,6 +39,41 @@ class OsPath private constructor(private val path: Path) : Path by path { 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 { + return path.iterator() + } + companion object { @JvmStatic fun of(path: String): OsPath { diff --git a/src/main/kotlin/com/mingliqiye/utils/random/RandomBytes.kt b/src/main/kotlin/com/mingliqiye/utils/random/Random.kt similarity index 99% rename from src/main/kotlin/com/mingliqiye/utils/random/RandomBytes.kt rename to src/main/kotlin/com/mingliqiye/utils/random/Random.kt index 361e119..5462b93 100644 --- a/src/main/kotlin/com/mingliqiye/utils/random/RandomBytes.kt +++ b/src/main/kotlin/com/mingliqiye/utils/random/Random.kt @@ -15,10 +15,11 @@ * * ProjectName mingli-utils * ModuleName mingli-utils.main - * CurrentFile RandomBytes.kt - * LastUpdate 2026-10-11 17:11:11 + * CurrentFile Random.kt + * LastUpdate 2026-10-20 20:05:37 * UpdateUser MingLiPro */ + package com.mingliqiye.utils.random import java.security.SecureRandom @@ -44,7 +45,7 @@ object Random { * 通过lazy委托延迟初始化 */ private val random: Random by lazy { - Random + Random.Default } /** diff --git a/src/main/kotlin/com/mingliqiye/utils/require/Require.kt b/src/main/kotlin/com/mingliqiye/utils/require/Require.kt deleted file mode 100644 index bad6eaa..0000000 --- a/src/main/kotlin/com/mingliqiye/utils/require/Require.kt +++ /dev/null @@ -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() - - @JvmStatic - var isLogError = true - - /** - * 检查条件是否满足,如果不满足则抛出指定类型的异常 - * @param value 要检查的布尔条件 - * @param throwable 异常类型Class对象 - * @param layzMessage 延迟消息构造器 - */ - @JvmStatic - @OptIn(ExperimentalContracts::class) - fun require(value: Boolean, throwable: Class, 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, 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) { - 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) { - 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 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 require(value: Boolean, layzMessage: RequireLayzMessageConstructor) { - contract { - returns() implies value - } - if (!value) throwThrowable(getExceptionConstructor().newInstance(layzMessage.call())) - } - - /** - * 获取指定异常类型的构造函数(内联泛型版本) - * @param T 异常类型 - * @return 异常类型的构造函数 - */ - @JvmName("__inline_GetExceptionConstructor") - @JvmStatic - inline fun getExceptionConstructor(): Constructor = - getExceptionConstructor(T::class.java) - - /** - * 获取指定异常类型的构造函数 - * @param throwable 异常类型Class对象 - * @return 异常类型的构造函数 - */ - @JvmStatic - @JvmName("__GetExceptionConstructor") - fun getExceptionConstructor(throwable: Class): Constructor = - throwable.getConstructor(String::class.java) - - /** - * 获取指定异常类型的构造函数 - * @param throwable 异常类型KClass对象 - * @return 异常类型的构造函数 - */ - @JvmStatic - @JvmName("__GetExceptionConstructor") - fun getExceptionConstructor(throwable: KClass): Constructor = - 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)) - } -} diff --git a/src/main/kotlin/com/mingliqiye/utils/require/RequireTrue.kt b/src/main/kotlin/com/mingliqiye/utils/require/RequireTrue.kt new file mode 100644 index 0000000..93d2075 --- /dev/null +++ b/src/main/kotlin/com/mingliqiye/utils/require/RequireTrue.kt @@ -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(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 { + return newRequired() +} + +fun newRequired(clazz: Class): Required { + return Required { + newException(clazz, it) + } +} + +inline fun newRequired(): Required { + return newRequired(T::class.java) +} + +fun newException(clazz: Class, 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 requireTrue(value: Boolean, clazz: Class, lazyMessage: () -> String) { + contract { + returns() implies value + } + if (!value) { + throw newException(clazz, lazyMessage()) + } +} + +@OptIn(ExperimentalContracts::class) +inline fun requireTrue(value: Boolean, noinline lazyMessage: () -> String) { + contract { + returns() implies value + } + requireTrue(value, T::class.java, lazyMessage) +} + +@OptIn(ExperimentalContracts::class) +fun Boolean.requireTrue(clazz: Class, lazyMessage: () -> String) { + contract { + returns() implies this@requireTrue + } + requireTrue(this, clazz, lazyMessage) +} + +@OptIn(ExperimentalContracts::class) +fun Boolean.requireTrue(clazz: Class, message: String) { + contract { + returns() implies this@requireTrue + } + requireTrue(this, clazz) { + message + } +} + +@OptIn(ExperimentalContracts::class) +fun requireTrue(value: Boolean, clazz: Class, message: String) { + contract { + returns() implies value + } + requireTrue(value, clazz) { message } +} + +@OptIn(ExperimentalContracts::class) +inline fun requireTrue(value: Boolean, message: String) { + contract { + returns() implies value + } + requireTrue(value, T::class.java) { message } +} + + +@OptIn(ExperimentalContracts::class) +inline fun Boolean.requireTrue(noinline lazyMessage: () -> String) { + contract { + returns() implies this@requireTrue + } + requireTrue(this, T::class.java, lazyMessage) + +} + +@OptIn(ExperimentalContracts::class) +inline fun Boolean.requireTrue(message: String) { + contract { + returns() implies this@requireTrue + } + requireTrue(this, T::class.java, message) + +} + +@OptIn(ExperimentalContracts::class) +fun requireTrue(value: Boolean, clazz: Class) { + contract { + returns() implies value + } + requireTrue(value, clazz) { DEFAULT_MESSAGE } +} + +@OptIn(ExperimentalContracts::class) +inline fun requireTrue(value: Boolean) { + contract { + returns() implies value + } + requireTrue(value, T::class.java) { DEFAULT_MESSAGE } +} + + +@OptIn(ExperimentalContracts::class) +fun Boolean.requireTrue(clazz: Class) { + contract { + returns() implies this@requireTrue + } + requireTrue(this, clazz) { DEFAULT_MESSAGE } + +} + +@OptIn(ExperimentalContracts::class) +inline fun Boolean.requireTrue() { + contract { + returns() implies this@requireTrue + } + requireTrue(this, T::class.java) { DEFAULT_MESSAGE } + +} diff --git a/src/main/kotlin/com/mingliqiye/utils/require/Required.kt b/src/main/kotlin/com/mingliqiye/utils/require/Required.kt new file mode 100644 index 0000000..60d3452 --- /dev/null +++ b/src/main/kotlin/com/mingliqiye/utils/require/Required.kt @@ -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 diff --git a/src/main/kotlin/com/mingliqiye/utils/stream/SuperStream.java b/src/main/kotlin/com/mingliqiye/utils/stream/SuperStream.java new file mode 100644 index 0000000..6939bff --- /dev/null +++ b/src/main/kotlin/com/mingliqiye/utils/stream/SuperStream.java @@ -0,0 +1,1236 @@ +/* + * 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 SuperStream.java + * LastUpdate 2026-10-20 20:05:37 + * UpdateUser MingLiPro + */ + +package com.mingliqiye.utils.stream; + +import com.mingliqiye.utils.collection.Collections; +import com.mingliqiye.utils.functions.P1Function; +import com.mingliqiye.utils.functions.P2Function; +import org.jetbrains.annotations.NotNull; + +import java.lang.reflect.Array; +import java.util.*; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.*; +import java.util.stream.*; + + +/** + * SuperStream是一个增强版的Stream包装器,提供了更多的便捷方法和重载方法来处理各种数据类型的流操作。 + * 它继承了Stream接口并实现了所有Stream的方法,同时添加了一些额外的便利功能。 + */ +public class SuperStream implements Stream { + + private final Stream stream; + + + /** + * 构造一个新的SuperStream实例 + * + * @param stream 被包装的基础Stream对象 + */ + private SuperStream(Stream stream) { + this.stream = stream; + } + + /** + * 创建一个包含指定整数元素的SuperStream + * + * @param args 可变参数的整数值数组 + * @return 包含指定整数的SuperStream实例 + */ + public static SuperStream of(int... args) { + return of(Collections.newArrayLists(args)); + } + + /** + * 创建一个包含指定字节元素的SuperStream + * + * @param args 可变参数的字节数组 + * @return 包含指定字节的SuperStream实例 + */ + public static SuperStream of(byte... args) { + return of(Collections.newArrayLists(args)); + } + + /** + * 创建一个包含指定短整数元素的SuperStream + * + * @param args 可变参数的短整数数组 + * @return 包含指定短整数的SuperStream实例 + */ + public static SuperStream of(short... args) { + return of(Collections.newArrayLists(args)); + } + + /** + * 创建一个包含指定字符元素的SuperStream + * + * @param args 可变参数的字符数组 + * @return 包含指定字符的SuperStream实例 + */ + public static SuperStream of(char... args) { + return of(Collections.newArrayLists(args)); + } + + /** + * 创建一个包含指定长整数元素的SuperStream + * + * @param args 可变参数的长整数数组 + * @return 包含指定长整数的SuperStream实例 + */ + public static SuperStream of(long... args) { + return of(Collections.newArrayLists(args)); + } + + /** + * 创建一个包含指定布尔元素的SuperStream + * + * @param args 可变参数的布尔数组 + * @return 包含指定布尔的SuperStream实例 + */ + public static SuperStream of(boolean... args) { + return of(Collections.newArrayLists(args)); + } + + + /** + * 创建一个包含指定浮点数元素的SuperStream + * + * @param args 可变参数的浮点数数组 + * @return 包含指定浮点数的SuperStream实例 + */ + public static SuperStream of(float... args) { + return of(Collections.newArrayLists(args)); + } + + /** + * 创建一个包含指定双精度浮点数元素的SuperStream + * + * @param args 可变参数的双精度浮点数数组 + * @return 包含指定双精度浮点数的SuperStream实例 + */ + public static SuperStream of(double... args) { + return of(Collections.newArrayLists(args)); + } + + + /** + * 将现有的Stream包装成SuperStream + * + * @param stream 需要包装的Stream对象 + * @param 流中元素的类型 + * @return 包装后的SuperStream实例 + */ + public static SuperStream of(Stream stream) { + return new SuperStream<>(stream); + } + + /** + * 创建一个包含指定数组元素的SuperStream,支持并行处理 + * + * @param ts 元素数组 + * @param parallel 是否使用并行流 + * @param 数组元素的类型 + * @return 包含指定数组元素的SuperStream实例 + */ + public static SuperStream of(T[] ts, boolean parallel) { + return of(Collections.newArrayLists(ts), parallel); + } + + /** + * 创建一个包含指定数组元素的SuperStream(默认串行) + * + * @param ts 元素数组 + * @param 数组元素的类型 + * @return 包含指定数组元素的SuperStream实例 + */ + public static SuperStream of(T[] ts) { + return of(ts, false); + } + + + /** + * 创建一个包含指定集合元素的SuperStream(默认串行) + * + * @param collection 包含元素的集合 + * @param 集合元素的类型 + * @return 包含指定集合元素的SuperStream实例 + */ + public static SuperStream of(Collection collection) { + return of(collection, false); + } + + + /** + * 创建一个包含指定Map键值对Entry的SuperStream(默认串行) + * + * @param map 源Map对象 + * @param Map的键类型 + * @param Map的值类型 + * @return 包含Map Entry的SuperStream实例 + */ + public static SuperStream> of(Map map) { + return of(map.entrySet(), false); + } + + + /** + * 创建一个包含指定Map键值对Entry的SuperStream,支持并行处理 + * + * @param map 源Map对象 + * @param parallel 是否使用并行流 + * @param Map的键类型 + * @param Map的值类型 + * @return 包含Map Entry的SuperStream实例 + */ + public static SuperStream> of(Map map, boolean parallel) { + return SuperStream.of(map.entrySet(), parallel); + } + + + /** + * 创建一个包含指定集合元素的SuperStream,支持并行处理 + * + * @param stream 包含元素的集合 + * @param parallel 是否使用并行流 + * @param 集合元素的类型 + * @return 包含指定集合元素的SuperStream实例 + */ + public static SuperStream of(Collection stream, boolean parallel) { + return parallel ? SuperStream.of(stream.parallelStream()) : SuperStream.of(stream.stream()); + } + + + /** + * 返回一个收集器,该收集器产生一个DoubleSummaryStatistics,描述输入元素的统计信息 + * + * @param mapper 用于将输入元素映射到double值的函数 + * @param 输入元素的类型 + * @return 产生DoubleSummaryStatistics的收集器 + */ + public static Collector summarizingDouble(@NotNull ToDoubleFunction mapper) { + return Collectors.summarizingDouble(mapper); + } + + + /** + * 返回一个收集器,该收集器产生一个LongSummaryStatistics,描述输入元素的统计信息 + * + * @param mapper 用于将输入元素映射到long值的函数 + * @param 输入元素的类型 + * @return 产生LongSummaryStatistics的收集器 + */ + public static Collector summarizingLong(@NotNull ToLongFunction mapper) { + return Collectors.summarizingLong(mapper); + } + + + /** + * 返回一个收集器,该收集器产生一个IntSummaryStatistics,描述输入元素的统计信息 + * + * @param mapper 用于将输入元素映射到int值的函数 + * @param 输入元素的类型 + * @return 产生IntSummaryStatistics的收集器 + */ + public static Collector summarizingInt(@NotNull ToIntFunction mapper) { + return Collectors.summarizingInt(mapper); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到ConcurrentMap中 + * + * @param keyMapper 用于产生键的映射函数 + * @param valueMapper 用于产生值的映射函数 + * @param mergeFunction 当键冲突时合并值的函数 + * @param mapSupplier 用于创建新Map的供应函数 + * @param 输入元素的类型 + * @param 键的类型 + * @param 值的类型 + * @param Map的具体类型 + * @return 产生ConcurrentMap的收集器 + */ + public static > Collector toConcurrentMap(@NotNull Function keyMapper, @NotNull Function valueMapper, @NotNull BinaryOperator mergeFunction, @NotNull Supplier mapSupplier) { + return Collectors.toConcurrentMap(keyMapper, valueMapper, mergeFunction, mapSupplier); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到ConcurrentMap中,使用BinaryOperator处理键冲突 + * + * @param keyMapper 用于产生键的映射函数 + * @param valueMapper 用于产生值的映射函数 + * @param mergeFunction 当键冲突时合并值的函数 + * @param 输入元素的类型 + * @param 键的类型 + * @param 值的类型 + * @return 产生ConcurrentMap的收集器 + */ + public static Collector> toConcurrentMap(@NotNull Function keyMapper, @NotNull Function valueMapper, @NotNull BinaryOperator mergeFunction) { + return Collectors.toConcurrentMap(keyMapper, valueMapper, mergeFunction); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到ConcurrentMap中,使用HashMap.merge处理键冲突 + * + * @param keyMapper 用于产生键的映射函数 + * @param valueMapper 用于产生值的映射函数 + * @param 输入元素的类型 + * @param 键的类型 + * @param 值的类型 + * @return 产生ConcurrentMap的收集器 + */ + public static Collector> toConcurrentMap(@NotNull Function keyMapper, @NotNull Function valueMapper) { + return Collectors.toConcurrentMap(keyMapper, valueMapper); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到Map中 + * + * @param keyMapper 用于产生键的映射函数 + * @param valueMapper 用于产生值的映射函数 + * @param mergeFunction 当键冲突时合并值的函数 + * @param mapSupplier 用于创建新Map的供应函数 + * @param 输入元素的类型 + * @param 键的类型 + * @param 值的类型 + * @param Map的具体类型 + * @return 产生Map的收集器 + */ + public static > Collector toMap(@NotNull Function keyMapper, @NotNull Function valueMapper, @NotNull BinaryOperator mergeFunction, @NotNull Supplier mapSupplier) { + return Collectors.toMap(keyMapper, valueMapper, mergeFunction, mapSupplier); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到Map中,使用BinaryOperator处理键冲突 + * + * @param keyMapper 用于产生键的映射函数 + * @param valueMapper 用于产生值的映射函数 + * @param mergeFunction 当键冲突时合并值的函数 + * @param 输入元素的类型 + * @param 键的类型 + * @param 值的类型 + * @return 产生Map的收集器 + */ + public static Collector> toMap(@NotNull Function keyMapper, @NotNull Function valueMapper, @NotNull BinaryOperator mergeFunction) { + return Collectors.toMap(keyMapper, valueMapper, mergeFunction); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到Map中,使用HashMap.merge处理键冲突 + * + * @param keyMapper 用于产生键的映射函数 + * @param valueMapper 用于产生值的映射函数 + * @param 输入元素的类型 + * @param 键的类型 + * @param 值的类型 + * @return 产生Map的收集器 + */ + public static Collector> toMap(@NotNull Function keyMapper, @NotNull Function valueMapper) { + return Collectors.toMap(keyMapper, valueMapper); + } + + + /** + * 返回一个收集器,该收集器根据谓词将输入元素分区到Map中 + * + * @param predicate 用于确定元素分区的谓词 + * @param downstream 应用于分区结果的下游收集器 + * @param 输入元素的类型 + * @param 下游收集器的结果类型 + * @param 下游收集器的累加器类型 + * @return 产生分区Map的收集器 + */ + public static Collector> partitioningBy(@NotNull Predicate predicate, @NotNull Collector downstream) { + return Collectors.partitioningBy(predicate, downstream); + } + + + /** + * 返回一个收集器,该收集器根据谓词将输入元素分区到Map中 + * + * @param predicate 用于确定元素分区的谓词 + * @param 输入元素的类型 + * @return 产生分区Map的收集器 + */ + public static Collector>> partitioningBy(@NotNull Predicate predicate) { + return Collectors.partitioningBy(predicate); + } + + + /** + * 返回一个收集器,该收集器将输入元素按分类器分组到ConcurrentMap中 + * + * @param classifier 用于分类元素的函数 + * @param mapFactory 用于创建Map的工厂函数 + * @param downstream 应用于分组结果的下游收集器 + * @param 输入元素的类型 + * @param 分类键的类型 + * @param 下游收集器的结果类型 + * @param 下游收集器的累加器类型 + * @param Map的具体类型 + * @return 产生ConcurrentMap的收集器 + */ + public static > Collector groupingByConcurrent(@NotNull Function classifier, @NotNull Supplier mapFactory, @NotNull Collector downstream) { + return Collectors.groupingByConcurrent(classifier, mapFactory, downstream); + } + + + /** + * 返回一个收集器,该收集器将输入元素按分类器分组到ConcurrentMap中 + * + * @param classifier 用于分类元素的函数 + * @param downstream 应用于分组结果的下游收集器 + * @param 输入元素的类型 + * @param 分类键的类型 + * @param 下游收集器的累加器类型 + * @param 下游收集器的结果类型 + * @return 产生ConcurrentMap的收集器 + */ + public static Collector> groupingByConcurrent(@NotNull Function classifier, @NotNull Collector downstream) { + return Collectors.groupingByConcurrent(classifier, downstream); + } + + + /** + * 返回一个收集器,该收集器将输入元素按分类器分组到ConcurrentMap中 + * + * @param classifier 用于分类元素的函数 + * @param 输入元素的类型 + * @param 分类键的类型 + * @return 产生ConcurrentMap的收集器 + */ + public static Collector>> groupingByConcurrent(@NotNull Function classifier) { + return Collectors.groupingByConcurrent(classifier); + } + + + /** + * 返回一个收集器,该收集器将输入元素按分类器分组到Map中 + * + * @param classifier 用于分类元素的函数 + * @param mapFactory 用于创建Map的工厂函数 + * @param downstream 应用于分组结果的下游收集器 + * @param 输入元素的类型 + * @param 分类键的类型 + * @param 下游收集器的结果类型 + * @param 下游收集器的累加器类型 + * @param Map的具体类型 + * @return 产生Map的收集器 + */ + public static > Collector groupingBy(@NotNull Function classifier, @NotNull Supplier mapFactory, @NotNull Collector downstream) { + return Collectors.groupingBy(classifier, mapFactory, downstream); + } + + + /** + * 返回一个收集器,该收集器将输入元素按分类器分组到Map中 + * + * @param classifier 用于分类元素的函数 + * @param downstream 应用于分组结果的下游收集器 + * @param 输入元素的类型 + * @param 分类键的类型 + * @param 下游收集器的累加器类型 + * @param 下游收集器的结果类型 + * @return 产生Map的收集器 + */ + public static Collector> groupingBy(@NotNull Function classifier, @NotNull Collector downstream) { + return Collectors.groupingBy(classifier, downstream); + } + + + /** + * 返回一个收集器,该收集器将输入元素按分类器分组到Map中 + * + * @param classifier 用于分类元素的函数 + * @param 输入元素的类型 + * @param 分类键的类型 + * @return 产生Map的收集器 + */ + public static Collector>> groupingBy(@NotNull Function classifier) { + return Collectors.groupingBy(classifier); + } + + + /** + * 返回一个收集器,该收集器执行归约操作 + * + * @param identity 归约操作的初始值 + * @param mapper 用于将输入元素映射到中间值的函数 + * @param op 用于组合中间值的二元操作符 + * @param 输入元素的类型 + * @param 中间值和结果的类型 + * @return 执行归约操作的收集器 + */ + public static Collector reducing(U identity, @NotNull Function mapper, @NotNull BinaryOperator op) { + return Collectors.reducing(identity, mapper, op); + } + + + /** + * 返回一个收集器,该收集器执行归约操作 + * + * @param op 用于组合元素的二元操作符 + * @param 输入元素的类型 + * @return 执行归约操作的收集器 + */ + public static Collector> reducing(@NotNull BinaryOperator op) { + return Collectors.reducing(op); + } + + + /** + * 返回一个收集器,该收集器执行归约操作 + * + * @param identity 归约操作的初始值 + * @param op 用于组合元素的二元操作符 + * @param 输入元素的类型 + * @return 执行归约操作的收集器 + */ + public static Collector reducing(T identity, @NotNull BinaryOperator op) { + return Collectors.reducing(identity, op); + } + + + /** + * 返回一个收集器,该收集器计算输入元素的平均值 + * + * @param mapper 用于将输入元素映射到double值的函数 + * @param 输入元素的类型 + * @return 计算平均值的收集器 + */ + public static Collector averagingDouble(@NotNull ToDoubleFunction mapper) { + return Collectors.averagingDouble(mapper); + } + + + /** + * 返回一个收集器,该收集器计算输入元素的平均值 + * + * @param mapper 用于将输入元素映射到long值的函数 + * @param 输入元素的类型 + * @return 计算平均值的收集器 + */ + public static Collector averagingLong(@NotNull ToLongFunction mapper) { + return Collectors.averagingLong(mapper); + } + + + /** + * 返回一个收集器,该收集器计算输入元素的平均值 + * + * @param mapper 用于将输入元素映射到int值的函数 + * @param 输入元素的类型 + * @return 计算平均值的收集器 + */ + public static Collector averagingInt(@NotNull ToIntFunction mapper) { + return Collectors.averagingInt(mapper); + } + + + /** + * 返回一个收集器,该收集器计算输入元素的总和 + * + * @param mapper 用于将输入元素映射到double值的函数 + * @param 输入元素的类型 + * @return 计算总和的收集器 + */ + public static Collector summingDouble(@NotNull ToDoubleFunction mapper) { + return Collectors.summingDouble(mapper); + } + + + /** + * 返回一个收集器,该收集器计算输入元素的总和 + * + * @param mapper 用于将输入元素映射到long值的函数 + * @param 输入元素的类型 + * @return 计算总和的收集器 + */ + public static Collector summingLong(@NotNull ToLongFunction mapper) { + return Collectors.summingLong(mapper); + } + + + /** + * 返回一个收集器,该收集器计算输入元素的总和 + * + * @param mapper 用于将输入元素映射到int值的函数 + * @param 输入元素的类型 + * @return 计算总和的收集器 + */ + public static Collector summingInt(@NotNull ToIntFunction mapper) { + return Collectors.summingInt(mapper); + } + + + /** + * 返回一个收集器,该收集器根据比较器找到最大元素 + * + * @param comparator 用于比较元素的比较器 + * @param 输入元素的类型 + * @return 找到最大元素的收集器 + */ + public static Collector> maxBy(@NotNull Comparator comparator) { + return Collectors.maxBy(comparator); + } + + + /** + * 返回一个收集器,该收集器根据比较器找到最小元素 + * + * @param comparator 用于比较元素的比较器 + * @param 输入元素的类型 + * @return 找到最小元素的收集器 + */ + public static Collector> minBy(@NotNull Comparator comparator) { + return Collectors.minBy(comparator); + } + + + /** + * 返回一个收集器,该收集器计算输入元素的数量 + * + * @param 输入元素的类型 + * @return 计算元素数量的收集器 + */ + public static Collector counting() { + return Collectors.counting(); + } + + + /** + * 返回一个收集器,该收集器在应用下游收集器后执行finisher转换 + * + * @param downstream 下游收集器 + * @param finisher 在下游收集器完成后应用的finisher函数 + * @param 输入元素的类型 + * @param 下游收集器的累加器类型 + * @param 下游收集器的结果类型 + * @param 最终结果类型 + * @return 执行转换的收集器 + */ + public static Collector collectingAndThen(@NotNull Collector downstream, @NotNull Function finisher) { + return Collectors.collectingAndThen(downstream, finisher); + } + + + /** + * 返回一个收集器,该收集器将输入元素映射后应用下游收集器 + * + * @param mapper 用于映射输入元素的函数 + * @param downstream 应用于映射后元素的下游收集器 + * @param 输入元素的类型 + * @param 映射后元素的类型 + * @param 下游收集器的累加器类型 + * @param 下游收集器的结果类型 + * @return 执行映射和收集的收集器 + */ + public static Collector mapping(@NotNull Function mapper, @NotNull Collector downstream) { + return Collectors.mapping(mapper, downstream); + } + + + /** + * 返回一个收集器,该收集器连接输入的字符序列 + * + * @param delimiter 分隔符 + * @param prefix 前缀 + * @param suffix 后缀 + * @return 连接字符序列的收集器 + */ + public static Collector joining(@NotNull CharSequence delimiter, @NotNull CharSequence prefix, @NotNull CharSequence suffix) { + return Collectors.joining(delimiter, prefix, suffix); + } + + + /** + * 返回一个收集器,该收集器连接输入的字符序列 + * + * @param delimiter 分隔符 + * @return 连接字符序列的收集器 + */ + public static Collector joining(@NotNull CharSequence delimiter) { + return Collectors.joining(delimiter); + } + + + /** + * 返回一个收集器,该收集器连接输入的字符序列 + * + * @return 连接字符序列的收集器 + */ + public static Collector joining() { + return Collectors.joining(); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到Set中 + * + * @param 输入元素的类型 + * @return 产生Set的收集器 + */ + public static Collector> toSet() { + return Collectors.toSet(); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到List中 + * + * @param 输入元素的类型 + * @return 产生List的收集器 + */ + public static Collector> toListCollector() { + return Collectors.toList(); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到指定类型的集合中 + * + * @param collectionFactory 用于创建集合的工厂函数 + * @param 输入元素的类型 + * @param 目标集合的具体类型 + * @return 产生指定类型集合的收集器 + */ + public static > Collector toCollection(@NotNull Supplier collectionFactory) { + return Collectors.toCollection(collectionFactory); + } + + + /** + * 返回一个收集器,该收集器将输入元素累积到Map中,键由keyMapper提供,值为元素本身 + * + * @param keyMapper 用于产生键的映射函数 + * @param 输入元素的类型 + * @param 键的类型 + * @return 产生Map的收集器 + */ + public static Collector> toMap(Function keyMapper) { + return toMap(keyMapper, Function.identity()); + } + + + /** + * 返回一个收集器,该收集器将Map.Entry类型的输入元素累积到Map中 + * + * @param 输入元素的类型(必须是Map.Entry) + * @param 键的类型 + * @param 值的类型 + * @return 产生Map的收集器 + */ + public static , K, V> Collector> toMap() { + return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue); + } + + /** + * 对流中的每个元素应用过滤条件 + * + * @param predicate 用于测试元素是否满足条件的谓词 + * @return 过滤后的SuperStream实例 + */ + public SuperStream filter(Predicate predicate) { + return SuperStream.of(stream.filter(predicate)); + } + + /** + * 使用指定的收集器对流进行收集操作 + * + * @param collector 用于收集元素的收集器 + * @param 收集结果的类型 + * @param 收集器累加器的类型 + * @return 收集操作的结果 + */ + public R collect(Collector collector) { + return stream.collect(collector); + } + + /** + * 获取流的Spliterator + * + * @return 流的Spliterator实例 + */ + @NotNull + public Spliterator spliterator() { + return stream.spliterator(); + } + + /** + * 将每个元素映射为IntStream并展平结果 + * + * @param mapper 用于将元素映射为IntStream的函数 + * @return 展平后的IntStream + */ + public IntStream flatMapToInt(Function mapper) { + return stream.flatMapToInt(mapper); + } + + /** + * 检查流是否为并行流 + * + * @return 如果流是并行的则返回true,否则返回false + */ + public boolean isParallel() { + return stream.isParallel(); + } + + /** + * 获取流的迭代器 + * + * @return 流的Iterator实例 + */ + @NotNull + public Iterator iterator() { + return stream.iterator(); + } + + /** + * 对流中的每个元素执行指定的动作 + * + * @param action 要执行的动作函数 + */ + public void forEach(P1Function action) { + stream.forEach(action::call); + } + + /** + * 对流中的每个元素执行指定的动作,并传递索引 + * + * @param action 要执行的动作函数,接收元素和索引作为参数 + */ + public void forEach(P2Function action) { + AtomicInteger i22 = new AtomicInteger(0); + stream.forEach(i -> { + action.call(i, i22.getAndAdd(1)); + }); + } + + /** + * 对流中的每个元素执行指定的动作 + * + * @param action 要执行的动作函数 + */ + public void forEach(Consumer action) { + stream.forEach(action); + } + + /** + * 将每个元素映射为Stream并展平结果 + * + * @param mapper 用于将元素映射为Stream的函数 + * @param 映射后元素的类型 + * @return 展平后的Stream实例 + */ + public Stream flatMap(Function> mapper) { + return stream.flatMap(mapper); + } + + /** + * 返回一个串行流 + * + * @return 串行的SuperStream实例 + */ + @NotNull + public SuperStream sequential() { + return SuperStream.of(stream.sequential()); + } + + /** + * 跳过指定数量的元素 + * + * @param n 要跳过的元素数量 + * @return 跳过元素后的SuperStream实例 + */ + public SuperStream skip(long n) { + return SuperStream.of(stream.skip(n)); + } + + /** + * 使用指定的收集器对流进行收集操作 + * + * @param supplier 用于创建初始累加器的供应函数 + * @param accumulator 用于将元素添加到累加器的操作 + * @param combiner 用于合并两个累加器的操作 + * @param 收集结果的类型 + * @return 收集操作的结果 + */ + public R collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner) { + return stream.collect(supplier, accumulator, combiner); + } + + /** + * 返回一个并行流 + * + * @return 并行的SuperStream实例 + */ + @NotNull + public SuperStream parallel() { + return SuperStream.of(stream.parallel()); + } + + /** + * 将每个元素映射为DoubleStream并展平结果 + * + * @param mapper 用于将元素映射为DoubleStream的函数 + * @return 展平后的DoubleStream + */ + public DoubleStream flatMapToDouble(Function mapper) { + return stream.flatMapToDouble(mapper); + } + + /** + * 将流转换为指定类型的数组 + * + * @param generator 用于创建数组的函数 + * @param 数组元素的类型 + * @return 转换后的数组 + */ + @NotNull + public A[] toArray(IntFunction generator) { + return stream.toArray(generator); + } + + /** + * 查找流中的第一个元素 + * + * @return 包含第一个元素的Optional,如果流为空则返回空Optional + */ + @NotNull + public Optional findFirst() { + return stream.findFirst(); + } + + /** + * 返回一个无序流 + * + * @return 无序的SuperStream实例 + */ + @NotNull + public SuperStream unordered() { + return SuperStream.of(stream.unordered()); + } + + /** + * 根据比较器查找流中的最小元素 + * + * @param comparator 用于比较元素的比较器 + * @return 包含最小元素的Optional,如果流为空则返回空Optional + */ + @NotNull + public Optional min(Comparator comparator) { + return stream.min(comparator); + } + + /** + * 查找流中的任意元素 + * + * @return 包含任意元素的Optional,如果流为空则返回空Optional + */ + @NotNull + public Optional findAny() { + return stream.findAny(); + } + + /** + * 注册一个关闭处理器,在流关闭时执行 + * + * @param closeHandler 关闭时要执行的Runnable + * @return 添加了关闭处理器的SuperStream实例 + */ + @NotNull + public SuperStream onClose(@NotNull Runnable closeHandler) { + return SuperStream.of(stream.onClose(closeHandler)); + } + + /** + * 将每个元素映射为LongStream并展平结果 + * + * @param mapper 用于将元素映射为LongStream的函数 + * @return 展平后的LongStream + */ + public LongStream flatMapToLong(Function mapper) { + return stream.flatMapToLong(mapper); + } + + /** + * 将流转换为指定类型的数组 + * + * @param clazz 数组元素的Class对象 + * @return 转换后的数组 + */ + @NotNull + @SuppressWarnings("unchecked") + public T[] toArray(Class clazz) { + return stream.toArray(i -> (T[]) Array.newInstance(clazz, i)); + } + + /** + * 将流转换为Object数组 + * + * @return 转换后的Object数组 + */ + @NotNull + public Object[] toArray() { + return stream.toArray(); + } + + /** + * 按顺序对流中的每个元素执行指定的动作 + * + * @param action 要执行的动作函数 + */ + public void forEachOrdered(Consumer action) { + stream.forEachOrdered(action); + } + + /** + * 关闭流并释放相关资源 + */ + public void close() { + stream.close(); + } + + /** + * 对流执行归约操作 + * + * @param accumulator 用于组合元素的二元操作符 + * @return 归约操作的结果,如果流为空则返回空Optional + */ + @NotNull + public Optional reduce(BinaryOperator accumulator) { + return stream.reduce(accumulator); + } + + /** + * 返回一个根据指定比较器排序的流 + * + * @param comparator 用于比较元素的比较器 + * @return 排序后的SuperStream实例 + */ + public SuperStream sorted(Comparator comparator) { + return SuperStream.of(stream.sorted(comparator)); + } + + /** + * 检查流中的所有元素是否都满足给定的谓词 + * + * @param predicate 用于测试元素的谓词 + * @return 如果所有元素都满足谓词或流为空则返回true,否则返回false + */ + public boolean allMatch(Predicate predicate) { + return stream.allMatch(predicate); + } + + /** + * 返回一个自然排序的流 + * + * @return 排序后的SuperStream实例 + */ + public SuperStream sorted() { + return SuperStream.of(stream.sorted()); + } + + /** + * 计算流中元素的数量 + * + * @return 流中元素的数量 + */ + public long count() { + return stream.count(); + } + + /** + * 将流中的每个元素通过映射函数转换 + * + * @param mapper 用于转换元素的映射函数 + * @param 映射后元素的类型 + * @return 转换后的SuperStream实例 + */ + public SuperStream map(Function mapper) { + return SuperStream.of(stream.map(mapper)); + } + + /** + * 对流执行归约操作 + * + * @param identity 归约操作的初始值 + * @param accumulator 用于组合元素的二元操作符 + * @return 归约操作的结果 + */ + public T reduce(T identity, BinaryOperator accumulator) { + return stream.reduce(identity, accumulator); + } + + /** + * 检查流中的所有元素都不满足给定的谓词 + * + * @param predicate 用于测试元素的谓词 + * @return 如果所有元素都不满足谓词则返回true,否则返回false + */ + public boolean noneMatch(Predicate predicate) { + return stream.noneMatch(predicate); + } + + /** + * 返回一个去重后的流 + * + * @return 去重后的SuperStream实例 + */ + public SuperStream distinct() { + return SuperStream.of(stream.distinct()); + } + + /** + * 根据比较器查找流中的最大元素 + * + * @param comparator 用于比较元素的比较器 + * @return 包含最大元素的Optional,如果流为空则返回空Optional + */ + @NotNull + public Optional max(Comparator comparator) { + return stream.max(comparator); + } + + /** + * 将流中的每个元素映射为double值 + * + * @param mapper 用于映射元素为double值的函数 + * @return 映射后的DoubleStream + */ + public DoubleStream mapToDouble(ToDoubleFunction mapper) { + return stream.mapToDouble(mapper); + } + + /** + * 限制流中元素的数量 + * + * @param maxSize 最大元素数量 + * @return 限制后的SuperStream实例 + */ + public SuperStream limit(long maxSize) { + return SuperStream.of(stream.limit(maxSize)); + } + + /** + * 将流中的每个元素映射为long值 + * + * @param mapper 用于映射元素为long值的函数 + * @return 映射后的LongStream + */ + public LongStream mapToLong(ToLongFunction mapper) { + return stream.mapToLong(mapper); + } + + /** + * 对流中的每个元素执行动作,然后返回原流 + * + * @param action 要执行的动作函数 + * @return 原始的SuperStream实例 + */ + public SuperStream peek(Consumer action) { + return SuperStream.of(stream.peek(action)); + } + + /** + * 对流执行归约操作 + * + * @param identity 归约操作的初始值 + * @param accumulator 用于组合元素的二元操作符 + * @param combiner 用于合并累加器的二元操作符 + * @param 累加器和结果的类型 + * @return 归约操作的结果 + */ + public U reduce(U identity, BiFunction accumulator, BinaryOperator combiner) { + return stream.reduce(identity, accumulator, combiner); + } + + /** + * 将流中的每个元素映射为int值 + * + * @param mapper 用于映射元素为int值的函数 + * @return 映射后的IntStream + */ + public IntStream mapToInt(ToIntFunction mapper) { + return stream.mapToInt(mapper); + } + + /** + * 检查流中是否有任何元素满足给定的谓词 + * + * @param predicate 用于测试元素的谓词 + * @return 如果有任何元素满足谓词则返回true,否则返回false + */ + public boolean anyMatch(Predicate predicate) { + return stream.anyMatch(predicate); + } + + /** + * 获取被包装的基础Stream对象 + * + * @return 基础Stream对象 + */ + public Stream getStream() { + return stream; + } + + /** + * 将流中的元素收集到Map中,使用指定的键和值映射函数 + * + * @param keyMapper 用于生成键的映射函数 + * @param valueMapper 用于生成值的映射函数 + * @param 键的类型 + * @param 值的类型 + * @return 包含映射结果的Map + */ + public Map toAMap(Function keyMapper, Function valueMapper) { + return collect(toMap(keyMapper, valueMapper)); + } + + /** + * 将流中的元素收集到Map中,使用指定的键映射函数,值为元素本身 + * + * @param keyMapper 用于生成键的映射函数 + * @param 键的类型 + * @return 包含映射结果的Map + */ + public Map toAMap(Function keyMapper) { + return collect(toMap(keyMapper)); + } + + /** + * 将流中的元素收集到List中 + * + * @return 包含流中所有元素的List + */ + public List toAList() { + return collect(toListCollector()); + } + +} diff --git a/src/main/java/com/mingliqiye/utils/stream/SuprtStreamUtils.kt b/src/main/kotlin/com/mingliqiye/utils/stream/SuprtStreamUtils.kt similarity index 100% rename from src/main/java/com/mingliqiye/utils/stream/SuprtStreamUtils.kt rename to src/main/kotlin/com/mingliqiye/utils/stream/SuprtStreamUtils.kt diff --git a/src/main/kotlin/com/mingliqiye/utils/system/SystemUtil.kt b/src/main/kotlin/com/mingliqiye/utils/system/SystemUtil.kt index 6c4f1f4..f3e1dfc 100644 --- a/src/main/kotlin/com/mingliqiye/utils/system/SystemUtil.kt +++ b/src/main/kotlin/com/mingliqiye/utils/system/SystemUtil.kt @@ -16,444 +16,271 @@ * ProjectName mingli-utils * ModuleName mingli-utils.main * CurrentFile SystemUtil.kt - * LastUpdate 2026-03-27 09:35:40 + * LastUpdate 2026-10-20 18:54:24 * UpdateUser MingLiPro */ @file:JvmName("SystemUtils") package com.mingliqiye.utils.system -import java.lang.management.ManagementFactory import java.net.* +import java.util.* 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 = Array(256) { "%02X".format(it) } + +private fun Enumeration?.toList(): List = + if (this == null) emptyList() else Collections.list(this) + /** * 操作系统名称属性,延迟初始化 */ val osName: String? by lazy { - System.getProperties().getProperty("os.name") + runCatching { System.getProperty("os.name") }.getOrNull() } /** - * 判断当前操作系统是否为Windows系统 - * - * @return 如果是Windows系统返回true,否则返回false + * 判断当前操作系统是否为 Windows */ val isWindows: Boolean by lazy { - osName != null && osName!!.startsWith("Windows") + osName?.startsWith("Windows") == true } /** - * 判断当前操作系统是否为Mac系统 - * - * @return 如果是Mac系统返回true,否则返回false + * 判断当前操作系统是否为 Mac */ val isMac: Boolean by lazy { - osName != null && osName!!.startsWith("Mac") + osName?.startsWith("Mac") == true } /** - * 判断当前操作系统是否为Unix/Linux系统 - * - * @return 如果是Unix/Linux系统返回true,否则返回false + * 判断当前操作系统是否为 Unix/Linux(含 macOS) */ val isUnix: Boolean by lazy { - if (osName == null) { - false - } else { - (osName!!.startsWith("Linux") || osName!!.startsWith("AIX") || osName!!.startsWith("SunOS") || osName!!.startsWith( - "Mac OS X" - ) || osName!!.startsWith( - "FreeBSD" - )) - } + val name = osName ?: return@lazy false + UNIX_PREFIXES.any { name.startsWith(it) } } /** - * JDK版本号属性,延迟初始化 + * JDK 版本号属性,延迟初始化 */ 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 version = jdkVersion - if (version == null || version.isEmpty()) { + if (version.isNullOrBlank()) { throw IllegalStateException( "Unable to determine Java version from property 'java.specification.version'" ) } - - val uversion: String = if (version.startsWith("1.")) { - if (version.length < 3) { - throw IllegalStateException( - "Invalid Java version format: $version" - ) - } - version[2] + "" - } else { - if (version.length < 2) { - throw IllegalStateException( - "Invalid Java version format: $version" - ) - } - version.take(2) - } - uversion.toInt() + val normalized = if (version.startsWith("1.")) version.substring(2) else version + val major = normalized.substringBefore('.').substringBefore('-') + major.toIntOrNull() + ?: throw IllegalStateException("Invalid Java version format: $version") } /** - * 判断当前JDK版本是否大于8 - * - * @return 如果JDK版本大于8返回true,否则返回false + * 判断当前 JDK 版本是否大于 8 */ val isJdk8Plus: Boolean by lazy { javaVersionAsInteger > 8 } /** - * 本地IP地址数组,延迟初始化 + * 本地 IPv4 地址数组,跳过回环、虚拟与未启用网卡 * - * @throws RuntimeException 当获取网络接口信息失败时抛出 + * @throws RuntimeException 网络接口枚举失败时抛出 */ val localIps: Array by lazy { try { - val ipList: MutableList = ArrayList() - val interfaces = NetworkInterface.getNetworkInterfaces() - - while (interfaces.hasMoreElements()) { - val networkInterface = interfaces.nextElement() - // 跳过回环接口和虚拟接口 - 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() + activeNetworkInterfaces() + .flatMap { it.inetAddresses.toList() } + .filterIsInstance() + .mapNotNull { it.hostAddress } + .toList() + .toTypedArray() } catch (e: SocketException) { throw RuntimeException("Failed to get local IP addresses", e) } } /** - * 本地IP地址列表,延迟初始化 + * 本地 IPv4 地址列表 */ -val localIpsByList: List by lazy { - localIps.toList() -} +val localIpsByList: List by lazy { localIps.toList() } /** - * 本地回环地址数组,延迟初始化 + * 本地回环地址数组;枚举失败时至少包含 `127.0.0.1` */ val loopbackIps: Array by lazy { - val strings: MutableList = ArrayList(3) - return@lazy try { - val interfaces = NetworkInterface.getNetworkInterfaces() - - while (interfaces.hasMoreElements()) { - val networkInterface = interfaces.nextElement() - - // 只处理回环接口 - if (networkInterface.isLoopback && networkInterface.isUp) { - val addresses = networkInterface.inetAddresses - - while (addresses.hasMoreElements()) { - val address = addresses.nextElement() - strings.add(address.hostAddress) - } - } - } - strings.toTypedArray() - } catch (e: SocketException) { + try { + NetworkInterface.getNetworkInterfaces().toList() + .asSequence() + .filter { it.isLoopback && it.isUp } + .flatMap { it.inetAddresses.toList().asSequence() } + .mapNotNull { it.hostAddress } + .toList() + .toTypedArray() + } catch (_: SocketException) { arrayOf("127.0.0.1") } } /** - * 本地回环地址IP列表,延迟初始化 + * 本地回环地址列表 */ -val loopbackIpsByList: List by lazy { - loopbackIps.toList() -} +val loopbackIpsByList: List by lazy { loopbackIps.toList() } /** - * 获取当前进程的PID - * - * @return 进程ID,如果无法获取则返回-1 + * 当前进程 PID;获取失败返回 -1 */ val getPid: Long by lazy { - try { - val name = ManagementFactory.getRuntimeMXBean().name - val index = name.indexOf('@') - if (index > 0) { - name.take(index).toLong() - } else { - -1L - } - } catch (e: Exception) { - -1L - } + runCatching { ProcessHandle.current().pid() }.getOrElse { -1L } } /** - * 获取当前进程的PID字符串形式 - * - * @return 进程ID字符串,如果无法获取则返回"-1" + * 当前进程 PID 字符串;获取失败返回 "-1" */ val pidAsString: String by lazy { - try { - val name = ManagementFactory.getRuntimeMXBean().name - val index = name.indexOf('@') - if (index > 0) { - name.take(index) - } else { - "-1" - } - } catch (e: Exception) { - "-1" - } + val pid = getPid + if (pid == -1L) "-1" else pid.toString() } /** - * 获取计算机名 - * - * @return 计算机名,如果无法获取则返回"unknown" + * 计算机名;获取失败返回 "unknown" */ val computerName: String by lazy { - try { - var name = System.getenv("COMPUTERNAME") - if (name.isNullOrBlank()) { - name = System.getenv("HOSTNAME") - } - if (name.isNullOrBlank()) { - name = InetAddress.getLocalHost().hostName - } - name ?: "unknown" - } catch (e: Exception) { - "unknown" - } + getEnvVar("COMPUTERNAME") + ?: getEnvVar("HOSTNAME") + ?: runCatching { InetAddress.getLocalHost().hostName }.getOrNull()?.takeIf { it.isNotBlank() } + ?: "unknown" } /** - * 获取当前用户名 - * - * @return 当前用户名,如果无法获取则返回"unknown" + * 当前用户名;获取失败返回 "unknown" */ val userName: String by lazy { - try { - getEnvVar("USERNAME") ?: getEnvVar("USER") ?: System.getProperty("user.name") ?: "unknown" - } catch (e: SecurityException) { - "unknown" - } catch (e: Exception) { - "unknown" - } + getEnvVar("USERNAME") + ?: getEnvVar("USER") + ?: runCatching { System.getProperty("user.name") }.getOrNull()?.takeIf { it.isNotBlank() } + ?: "unknown" } -private fun getEnvVar(name: String): String? { - return try { - System.getenv(name)?.takeIf { it.isNotBlank() } - } catch (e: SecurityException) { - null - } -} +private fun getEnvVar(name: String): String? = runCatching { + System.getenv(name)?.takeIf { it.isNotBlank() } +}.getOrNull() /** - * 获取本机MAC地址的字节数组形式 + * 本机 MAC 地址字节数组 * - * @return MAC地址字节数组,如果无法获取则返回空数组 + * 未找到可用网卡时回退为 6 字节随机数,避免下游拿到空数组导致错误。 */ val macAddressBytes: ByteArray by lazy { - try { - val interfaces = NetworkInterface.getNetworkInterfaces() - - while (interfaces.hasMoreElements()) { - val networkInterface = interfaces.nextElement() - - // 跳过回环接口和虚拟接口 - 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) + val found = try { + activeNetworkInterfaces() + .mapNotNull { runCatching { it.hardwareAddress }.getOrNull() } + .firstOrNull { it.isNotEmpty() } + } catch (_: SocketException) { + null } + found ?: randomByte(6) } /** - * 获取本机MAC地址的十六进制字符串列表形式 - * - * @return MAC地址字符串列表,每个元素表示一个字节的十六进制值(大写),如果无法获取则返回空列表 + * 本机 MAC 地址的十六进制字符串列表(大写) */ val macAddressStringList: List by lazy { - val macBytes = macAddressBytes - if (macBytes.isEmpty()) { - return@lazy emptyList() - } - - macBytes.map { String.format("%02X", it) } + macAddressBytes.map { HEX_UPPER[it.toInt() and 0xFF] } } /** - * 获取本机MAC地址的格式化字符串形式(如 "00:11:22:33:44:55") - * - * @return 格式化的MAC地址字符串,如果无法获取则返回空字符串 + * 本机 MAC 地址的格式化字符串,如 `00:11:22:33:44:55` */ val macAddressFormattedString: String by lazy { - val macBytes = macAddressBytes - if (macBytes.isEmpty()) { - return@lazy "" - } - - macBytes.joinToString(":") { String.format("%02X", it) } + macAddressBytes.joinToString(":") { HEX_UPPER[it.toInt() and 0xFF] } } /** - * 获取所有网络接口的MAC地址映射 - * - * @return Map结构,key为网络接口名称,value为对应的MAC地址字节数组 + * 所有非回环、非虚拟网卡的 MAC 地址映射,key 为网卡名 */ val allMacAddresses: Map by lazy { try { - val result = mutableMapOf() - val interfaces = NetworkInterface.getNetworkInterfaces() - - while (interfaces.hasMoreElements()) { - val networkInterface = interfaces.nextElement() - - // 跳过回环接口和虚拟接口 - if (networkInterface.isLoopback || networkInterface.isVirtual) { - continue + NetworkInterface.getNetworkInterfaces().toList() + .asSequence() + .filter { !it.isLoopback && !it.isVirtual } + .mapNotNull { ni -> + val mac = runCatching { ni.hardwareAddress }.getOrNull() + if (mac != null && mac.isNotEmpty()) ni.name to mac else null } - - val mac = networkInterface.hardwareAddress - if (mac != null && mac.isNotEmpty()) { - result[networkInterface.name] = mac - } - } - - result - } catch (e: SocketException) { - emptyMap() - } catch (e: Exception) { + .toMap() + } catch (_: SocketException) { emptyMap() } } /** - * 获取所有网络接口的MAC地址字符串列表映射 - * - * @return Map结构,key为网络接口名称,value为对应的MAC地址字符串列表 + * 所有网卡 MAC 地址的十六进制字符串列表映射 */ val allMacAddressesStringList: Map> by lazy { - allMacAddresses.mapValues { entry -> - entry.value.map { String.format("%02X", it) } - } + allMacAddresses.mapValues { (_, bytes) -> bytes.map { HEX_UPPER[it.toInt() and 0xFF] } } } /** - * 获取可用处理器数量的懒加载属性 + * 可用处理器数量 */ val availableProcessors: Int by lazy { Runtime.getRuntime().availableProcessors() } - -private var isLoadprotocol = false -private var protocol = "" +private fun activeNetworkInterfaces(): Sequence = + NetworkInterface.getNetworkInterfaces().toList().asSequence() + .filter { !it.isLoopback && !it.isVirtual && it.isUp } -/** - * 判断是否为开发模式(file协议) - */ -val isDevMode: Boolean by lazy { - protocol == "file" +private val protocol: String by lazy { + val target = ProtocolAnchor::class.java + val resourceName = target.simpleName + ".class" + val resource: URL = target.getResource(resourceName) + ?: throw IllegalStateException( + "Unable to locate resource '$resourceName' for class ${target.name}" + ) + resource.protocol } -/** - * 判断是否不为开发模式 - */ -val isNotDevMode: Boolean by lazy { - protocol != "file" -} -/** - * 判断是否为JAR模式 - */ -val isJarMode: Boolean by lazy { - protocol == "jar" -} +/** 是否为开发模式(file 协议) */ +val isDevMode: Boolean get() = protocol == "file" -/** - * 判断是否不为JAR模式 - */ -val isNotJarMode: Boolean by lazy { - protocol != "jar" -} +/** 是否不为开发模式 */ +val isNotDevMode: Boolean get() = protocol != "file" -/** - * 判断是否为WAR模式 - */ -val isWarMode: Boolean by lazy { - protocol == "war" -} +/** 是否为 JAR 模式 */ +val isJarMode: Boolean get() = protocol == "jar" -/** - * 判断是否不为WAR模式 - */ -val isNotMode: Boolean by lazy { - protocol != "war" -} +/** 是否不为 JAR 模式 */ +val isNotJarMode: Boolean get() = protocol != "jar" -/** - * 判断是否为JSWAR模式 - */ -val isJswarMode: Boolean by lazy { - protocol == "jswar" -} +/** 是否为 WAR 模式 */ +val isWarMode: Boolean get() = protocol == "war" -/** - * 判断是否不为JSWAR模式 - */ -val isNotJswarMode: Boolean by lazy { - protocol != "jswar" -} +/** 是否不为 WAR 模式 */ +val isNotWarMode: Boolean get() = protocol != "war" -/** - * 加载并获取资源协议 - * @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 - return protocol.let { - isLoadprotocol = true - it - } -} +/** 是否为 JSWAR 模式 */ +val isJswarMode: Boolean get() = protocol == "jswar" + +/** 是否不为 JSWAR 模式 */ +val isNotJswarMode: Boolean get() = protocol != "jswar" + + +private object ProtocolAnchor