diff --git a/NOTICE b/NOTICE index a7b064f..53b9a98 100644 --- a/NOTICE +++ b/NOTICE @@ -1,5 +1,5 @@ mingli-utils -Copyright 2025 mingliqiye +Copyright 2026 mingliqiye This product includes software developed by third parties. The original copyright notices and licenses are reproduced below. diff --git a/build.gradle.kts b/build.gradle.kts index a60de06..029ff0e 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -16,7 +16,7 @@ * ProjectName mingli-utils * ModuleName mingli-utils * CurrentFile build.gradle.kts - * LastUpdate 2026-11-18 08:42:41 + * LastUpdate 2026-11-22 07:59:57 * UpdateUser MingLiPro */ @@ -111,8 +111,11 @@ dependencies { compileOnly("com.baomidou:mybatis-plus-extension:3.5.15") compileOnly("com.baomidou:mybatis-plus-jsqlparser:3.5.15") compileOnly("com.baomidou:mybatis-plus-spring:3.5.9") + compileOnly("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2") + compileOnly("org.jetbrains.kotlinx:kotlinx-coroutines-reactor:1.10.2") testImplementation("org.junit.jupiter:junit-jupiter:5.7.1") testRuntimeOnly("org.junit.platform:junit-platform-launcher") + testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2") testImplementation("com.mingliqiye.logger:logger-log4j2:1.0.9") testImplementation("com.google.code.gson:gson:2.13.2") diff --git a/gradle.properties b/gradle.properties index 3d3935e..b9f31ff 100644 --- a/gradle.properties +++ b/gradle.properties @@ -16,10 +16,10 @@ # ProjectName mingli-utils # ModuleName mingli-utils # CurrentFile gradle.properties -# LastUpdate 2026-11-18 19:46:50 +# LastUpdate 2026-11-23 09:56:18 # UpdateUser MingLiPro # JDKVERSIONS=17 GROUPSID=com.mingliqiye.utils ARTIFACTID=mingli-utils -VERSIONS=5.5.5 +VERSIONS=5.6.0 diff --git a/src/main/java/com/mingliqiye/utils/stream/SuperStream.java b/src/main/java/com/mingliqiye/utils/stream/SuperStream.java index 413787e..b107cb8 100644 --- a/src/main/java/com/mingliqiye/utils/stream/SuperStream.java +++ b/src/main/java/com/mingliqiye/utils/stream/SuperStream.java @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. * - * ProjectName FastBaseMapper.kt + * ProjectName mingli-utils * ModuleName mingli-utils.main * CurrentFile SuperStream.java - * LastUpdate 2026-10-26 23:22:18 + * LastUpdate 2026-11-22 10:10:33 * UpdateUser MingLiPro */ @@ -26,6 +26,7 @@ import com.mingliqiye.utils.collection.Collections; import com.mingliqiye.utils.functions.P1Function; import com.mingliqiye.utils.functions.P2Function; import org.jetbrains.annotations.NotNull; +import org.jspecify.annotations.NonNull; import java.lang.reflect.Array; import java.util.*; @@ -987,7 +988,7 @@ public class SuperStream implements Stream { */ @NotNull @SuppressWarnings("unchecked") - public T[] toArray(Class clazz) { + public T @NonNull [] toArray(Class clazz) { return stream.toArray(i -> (T[]) Array.newInstance(clazz, i)); } @@ -997,7 +998,7 @@ public class SuperStream implements Stream { * @return 转换后的Object数组 */ @NotNull - public Object[] toArray() { + public Object @NonNull [] toArray() { return stream.toArray(); } diff --git a/src/main/kotlin/com/mingliqiye/utils/collection/Collection.kt b/src/main/kotlin/com/mingliqiye/utils/collection/Collection.kt index ad35573..75ae9a8 100644 --- a/src/main/kotlin/com/mingliqiye/utils/collection/Collection.kt +++ b/src/main/kotlin/com/mingliqiye/utils/collection/Collection.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 Collection.kt - * LastUpdate 2025-09-21 14:36:57 + * LastUpdate 2026-11-23 07:33:23 * UpdateUser MingLiPro */ @@ -745,6 +745,38 @@ fun newStack(elements: Collection): Stack { } +/** + * 创建一个新的 ArrayDeque 实例。 + * + * @param T 元素类型 + * @return 新创建的 ArrayDeque + */ +fun newArrayDeque(): ArrayDeque { + return ArrayDeque() +} + +/** + * 使用可变参数创建一个新的 ArrayDeque 实例。 + * + * @param T 元素类型 + * @param elements 可变参数列表 + * @return 新创建的 ArrayDeque + */ +fun newArrayDeque(vararg elements: T): ArrayDeque { + return newArrayDeque(elements.toList()) +} + +/** + * 将集合转换为新的 ArrayDeque 实例。 + * + * @param T 元素类型 + * @param elements 输入集合 + * @return 新创建的 ArrayDeque + */ +fun newArrayDeque(elements: Collection): ArrayDeque { + return ArrayDeque(elements) +} + /** * 创建一个新的 TreeSet 实例,并指定比较器。 * @@ -980,9 +1012,9 @@ fun toArray(list: List): CharArray { * @param list 输入的 List * @return 转换后的数组 */ -inline fun toArray(list: List): Array { +inline fun toArray(list: List): Array { if (list.isEmpty()) - return arrayOf() + return arrayOf() return SuperStream.of(list) .toArray(T::class.java) } @@ -995,7 +1027,7 @@ inline fun toArray(list: List): Array { * @param clazz 数组元素类型对应的 Class 对象 * @return 转换后的数组 */ -fun toArray(list: List, clazz: Class): Array { +fun toArray(list: List, clazz: Class): Array { return SuperStream.of(list) .toArray(clazz) } diff --git a/src/main/kotlin/com/mingliqiye/utils/foreach/ForEach.kt b/src/main/kotlin/com/mingliqiye/utils/foreach/ForEach.kt deleted file mode 100644 index 31c482d..0000000 --- a/src/main/kotlin/com/mingliqiye/utils/foreach/ForEach.kt +++ /dev/null @@ -1,707 +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 ForEach.kt - * LastUpdate 2026-02-27 12:45:39 - * UpdateUser MingLiPro - */ -@file:JvmName("ForEach") - -package com.mingliqiye.utils.foreach - -import com.mingliqiye.utils.functions.* - - -/** - * 对给定的可迭代对象执行指定的操作,同时处理元素值和索引。 - * 根据可迭代对象是否实现 RandomAccess 接口选择最优的遍历方式。 - * - * @param iterable 要遍历的可迭代对象 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数 - * @param 可迭代对象中元素的类型 - */ -fun forEach( - iterable: Iterable, action: P2Function, -) { - when (iterable) { - is RandomAccess if iterable is MutableList<*> -> { - // 如果是支持随机访问的可变列表,则使用索引遍历以提高性能 - val list = iterable as MutableList - for (i in list.indices) { - action.call(list[i], i) - } - } - - is MutableList<*> -> { - // 对于普通可变列表,使用迭代器进行遍历,并手动维护索引 - var index = 0 - val it = iterable.iterator() - while (it.hasNext()) { - action.call(it.next(), index) - index++ - } - } - - else -> { - // 对于其他类型的可迭代对象,使用增强 for 循环并手动维护索引 - for ((index, element) in iterable.withIndex()) { - action.call(element, index) - } - } - } -} - -/** - * 对给定的可迭代对象执行指定的操作,仅处理元素值。 - * 根据可迭代对象是否实现 RandomAccess 接口选择最优的遍历方式。 - * - * @param iterable 要遍历的可迭代对象 - * @param action 要对每个元素执行的操作,只接收元素值作为参数 - * @param 可迭代对象中元素的类型 - */ -fun forEach( - iterable: Iterable, action: P1Function, -) { - if (iterable is RandomAccess) { - // 如果是支持随机访问的列表,则使用索引遍历以提高性能 - val list = iterable as MutableList - for (i in list.indices) { - action.call(list[i]) - } - } else { - // 否则使用增强 for 循环进行遍历 - for (element in iterable) { - action.call(element) - } - } -} - -/** - * 对给定的可迭代对象执行指定的操作,同时处理元素值和索引。 - * 如果操作返回 true,则提前终止遍历。 - * 根据可迭代对象是否实现 RandomAccess 接口选择最优的遍历方式。 - * - * @param iterable 要遍历的可迭代对象 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止 - * @param 可迭代对象中元素的类型 - */ -fun forEachB( - iterable: Iterable, action: P2RFunction, -) { - when (iterable) { - is RandomAccess if iterable is MutableList<*> -> { - // 如果是支持随机访问的可变列表,则使用索引遍历以提高性能 - val list = iterable as MutableList - for (i in list.indices) { - if (action.call(list[i], i)) return - } - } - - is MutableList<*> -> { - // 对于普通可变列表,使用迭代器进行遍历,并手动维护索引 - var index = 0 - val it = iterable.iterator() - while (it.hasNext()) { - if (action.call(it.next(), index)) return - index++ - } - } - - else -> { - // 对于其他类型的可迭代对象,使用增强 for 循环并手动维护索引 - var index = 0 - for (element in iterable) { - if (action.call(element, index)) return - index++ - } - } - } -} - -/** - * 对给定的可迭代对象执行指定的操作,仅处理元素值。 - * 如果操作返回 true,则提前终止遍历。 - * 根据可迭代对象是否实现 RandomAccess 接口选择最优的遍历方式。 - * - * @param iterable 要遍历的可迭代对象 - * @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止 - * @param 可迭代对象中元素的类型 - */ -fun forEachB( - iterable: Iterable, action: P1RFunction, -) { - if (iterable is RandomAccess) { - // 如果是支持随机访问的列表,则使用索引遍历以提高性能 - val list = iterable as MutableList - for (i in list.indices) { - if (action.call(list[i])) return - } - } else { - // 否则使用增强 for 循环进行遍历 - for (element in iterable) { - if (action.call(element)) return - } - } -} - -/** - * 对给定的数组执行指定的操作,同时处理元素值和索引。 - * - * @param array 要遍历的数组 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数 - * @param 数组中元素的类型 - */ -fun forEach( - array: Array, action: P2Function, -) { - forEach(array.toList(), action) -} - -/** - * 对给定的数组执行指定的操作,仅处理元素值。 - * - * @param array 要遍历的数组 - * @param action 要对每个元素执行的操作,只接收元素值作为参数 - * @param 数组中元素的类型 - */ -fun forEach( - array: Array, action: P1Function, -) { - forEach(array.toList(), action) -} - -/** - * 对给定的数组执行指定的操作,同时处理元素值和索引。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的数组 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止 - * @param 数组中元素的类型 - */ -fun forEachB( - array: Array, action: P2RFunction, -) { - forEachB(array.toList(), action) -} - -/** - * 对给定的数组执行指定的操作,仅处理元素值。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的数组 - * @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止 - * @param 数组中元素的类型 - */ -fun forEachB( - array: Array, action: P1RFunction, -) { - forEachB(array.toList(), action) -} - -/** - * 对给定的字节数组执行指定的操作,同时处理元素值和索引。 - * - * @param array 要遍历的字节数组 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数 - */ -fun forEach( - array: ByteArray, action: P2Function, -) { - forEach(array.toList(), action) -} - -/** - * 对给定的字节数组执行指定的操作,仅处理元素值。 - * - * @param array 要遍历的字节数组 - * @param action 要对每个元素执行的操作,只接收元素值作为参数 - */ -fun forEach( - array: ByteArray, action: P1Function, -) { - forEach(array.toList(), action) -} - -/** - * 对给定的字节数组执行指定的操作,同时处理元素值和索引。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的字节数组 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止 - */ -fun forEachB( - array: ByteArray, action: P2RFunction, -) { - forEachB(array.toList(), action) -} - -/** - * 对给定的字节数组执行指定的操作,仅处理元素值。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的字节数组 - * @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止 - */ -fun forEachB( - array: ByteArray, action: P1RFunction, -) { - forEachB(array.toList(), action) -} - -/** - * 对给定的字符数组执行指定的操作,同时处理元素值和索引。 - * - * @param array 要遍历的字符数组 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数 - */ -fun forEach( - array: CharArray, action: P2Function, -) { - forEach(array.toList(), action) -} - -/** - * 对给定的字符数组执行指定的操作,仅处理元素值。 - * - * @param array 要遍历的字符数组 - * @param action 要对每个元素执行的操作,只接收元素值作为参数 - */ -fun forEach( - array: CharArray, action: P1Function, -) { - forEach(array.toList(), action) -} - -/** - * 对给定的字符数组执行指定的操作,同时处理元素值和索引。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的字符数组 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止 - */ -fun forEachB( - array: CharArray, action: P2RFunction, -) { - forEachB(array.toList(), action) -} - -/** - * 对给定的字符数组执行指定的操作,仅处理元素值。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的字符数组 - * @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止 - */ -fun forEachB( - array: CharArray, action: P1RFunction, -) { - forEachB(array.toList(), action) -} - -/** - * 对给定的整型数组执行指定的操作,同时处理元素值和索引。 - * - * @param array 要遍历的整型数组 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数 - */ -fun forEach( - array: IntArray, action: P2Function, -) { - forEach(array.toList(), action) -} - -/** - * 对给定的整型数组执行指定的操作,仅处理元素值。 - * - * @param array 要遍历的整型数组 - * @param action 要对每个元素执行的操作,只接收元素值作为参数 - */ -fun forEach( - array: IntArray, action: P1Function, -) { - forEach(array.toList(), action) -} - -/** - * 对给定的整型数组执行指定的操作,同时处理元素值和索引。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的整型数组 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止 - */ -fun forEachB( - array: IntArray, action: P2RFunction, -) { - forEachB(array.toList(), action) -} - -/** - * 对给定的整型数组执行指定的操作,仅处理元素值。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的整型数组 - * @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止 - */ -fun forEachB( - array: IntArray, action: P1RFunction, -) { - forEachB(array.toList(), action) -} - -/** - * 对给定的长整型数组执行指定的操作,同时处理元素值和索引。 - * - * @param array 要遍历的长整型数组 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数 - */ -fun forEach( - array: LongArray, action: P2Function, -) { - forEach(array.toList(), action) -} - -/** - * 对给定的长整型数组执行指定的操作,仅处理元素值。 - * - * @param array 要遍历的长整型数组 - * @param action 要对每个元素执行的操作,只接收元素值作为参数 - */ -fun forEach( - array: LongArray, action: P1Function, -) { - forEach(array.toList(), action) -} - -/** - * 对给定的长整型数组执行指定的操作,同时处理元素值和索引。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的长整型数组 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止 - */ -fun forEachB( - array: LongArray, action: P2RFunction, -) { - forEachB(array.toList(), action) -} - -/** - * 对给定的长整型数组执行指定的操作,仅处理元素值。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的长整型数组 - * @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止 - */ -fun forEachB( - array: LongArray, action: P1RFunction, -) { - forEachB(array.toList(), action) -} - -/** - * 对给定的短整型数组执行指定的操作,同时处理元素值和索引。 - * - * @param array 要遍历的短整型数组 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数 - */ -fun forEach( - array: ShortArray, action: P2Function, -) { - forEach(array.toList(), action) -} - -/** - * 对给定的短整型数组执行指定的操作,仅处理元素值。 - * - * @param array 要遍历的短整型数组 - * @param action 要对每个元素执行的操作,只接收元素值作为参数 - */ -fun forEach( - array: ShortArray, action: P1Function, -) { - forEach(array.toList(), action) -} - -/** - * 对给定的短整型数组执行指定的操作,同时处理元素值和索引。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的短整型数组 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止 - */ -fun forEachB( - array: ShortArray, action: P2RFunction, -) { - forEachB(array.toList(), action) -} - -/** - * 对给定的短整型数组执行指定的操作,仅处理元素值。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的短整型数组 - * @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止 - */ -fun forEachB( - array: ShortArray, action: P1RFunction, -) { - forEachB(array.toList(), action) -} - -/** - * 对给定的浮点数组执行指定的操作,同时处理元素值和索引。 - * - * @param array 要遍历的浮点数组 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数 - */ -fun forEach( - array: FloatArray, action: P2Function, -) { - forEach(array.toList(), action) -} - -/** - * 对给定的浮点数组执行指定的操作,仅处理元素值。 - * - * @param array 要遍历的浮点数组 - * @param action 要对每个元素执行的操作,只接收元素值作为参数 - */ -fun forEach( - array: FloatArray, action: P1Function, -) { - forEach(array.toList(), action) -} - -/** - * 对给定的浮点数组执行指定的操作,同时处理元素值和索引。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的浮点数组 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止 - */ -fun forEachB( - array: FloatArray, action: P2RFunction, -) { - forEachB(array.toList(), action) -} - -/** - * 对给定的浮点数组执行指定的操作,仅处理元素值。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的浮点数组 - * @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止 - */ -fun forEachB( - array: FloatArray, action: P1RFunction, -) { - forEachB(array.toList(), action) -} - -/** - * 对给定的双精度浮点数组执行指定的操作,同时处理元素值和索引。 - * - * @param array 要遍历的双精度浮点数组 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数 - */ -fun forEach( - array: DoubleArray, action: P2Function, -) { - forEach(array.toList(), action) -} - -/** - * 对给定的双精度浮点数组执行指定的操作,仅处理元素值。 - * - * @param array 要遍历的双精度浮点数组 - * @param action 要对每个元素执行的操作,只接收元素值作为参数 - */ -fun forEach( - array: DoubleArray, action: P1Function, -) { - forEach(array.toList(), action) -} - -/** - * 对给定的双精度浮点数组执行指定的操作,同时处理元素值和索引。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的双精度浮点数组 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止 - */ -fun forEachB( - array: DoubleArray, action: P2RFunction, -) { - forEachB(array.toList(), action) -} - -/** - * 对给定的双精度浮点数组执行指定的操作,仅处理元素值。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的双精度浮点数组 - * @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止 - */ -fun forEachB( - array: DoubleArray, action: P1RFunction, -) { - forEachB(array.toList(), action) -} - -/** - * 对给定的布尔数组执行指定的操作,同时处理元素值和索引。 - * - * @param array 要遍历的布尔数组 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数 - */ -fun forEach( - array: BooleanArray, action: P2Function, -) { - forEach(array.toList(), action) -} - -/** - * 对给定的布尔数组执行指定的操作,仅处理元素值。 - * - * @param array 要遍历的布尔数组 - * @param action 要对每个元素执行的操作,只接收元素值作为参数 - */ -fun forEach( - array: BooleanArray, action: P1Function, -) { - forEach(array.toList(), action) -} - -/** - * 对给定的布尔数组执行指定的操作,同时处理元素值和索引。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的布尔数组 - * @param action 要对每个元素执行的操作,接收元素值和索引作为参数,返回 Boolean 表示是否提前终止 - */ -fun forEachB( - array: BooleanArray, action: P2RFunction, -) { - forEachB(array.toList(), action) -} - -/** - * 对给定的布尔数组执行指定的操作,仅处理元素值。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的布尔数组 - * @param action 要对每个元素执行的操作,只接收元素值作为参数,返回 Boolean 表示是否提前终止 - */ -fun forEachB( - array: BooleanArray, action: P1RFunction, -) { - forEachB(array.toList(), action) -} - -/** - * 对给定的键值对集合执行指定的操作,同时处理键、值和索引。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的键值对集合 - * @param action 要对每个键值对执行的操作,接收键、值和索引作为参数,返回 Boolean 表示是否提前终止 - * @param 键的类型 - * @param 值的类型 - * @param 集合的具体类型 - */ -fun >> forEachB( - array: A, action: P3RFunction, -) { - forEachB(array, P2RFunction, Int, Boolean> { p1, p2 -> action.call(p1.key, p1.value, p2) }) -} - -/** - * 对给定的映射执行指定的操作,同时处理键、值和索引。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param map 要遍历的映射 - * @param action 要对每个键值对执行的操作,接收键、值和索引作为参数,返回 Boolean 表示是否提前终止 - * @param 键的类型 - * @param 值的类型 - * @param 映射的具体类型 - */ -fun > forEachB( - map: A, action: P3RFunction, -) { - forEachB(map.entries, P2RFunction, Int, Boolean> { p1, p2 -> action.call(p1.key, p1.value, p2) }) -} - -/** - * 对给定的键值对集合执行指定的操作,仅处理键和值。 - * - * @param array 要遍历的键值对集合 - * @param action 要对每个键值对执行的操作,接收键和值作为参数 - * @param 键的类型 - * @param 值的类型 - * @param 集合的具体类型 - */ -fun >> forEachMap( - array: A, action: P2Function, -) { - forEach(array, P1Function> { p1 -> action.call(p1.key, p1.value) }) -} - -/** - * 对给定的映射执行指定的操作,仅处理键和值。 - * - * @param map 要遍历的映射 - * @param action 要对每个键值对执行的操作,接收键和值作为参数 - * @param 键的类型 - * @param 值的类型 - * @param 映射的具体类型 - */ -fun > forEachMap( - map: A, action: P2Function, -) { - forEach(map.entries, P1Function> { p1 -> action.call(p1.key, p1.value) }) -} - -/** - * 对给定的键值对集合执行指定的操作,仅处理键和值。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param array 要遍历的键值对集合 - * @param action 要对每个键值对执行的操作,接收键和值作为参数,返回 Boolean 表示是否提前终止 - * @param 键的类型 - * @param 值的类型 - * @param 集合的具体类型 - */ -fun >> forEachMapB( - array: A, action: P2RFunction, -) { - forEachB(array, P1RFunction, Boolean> { p1 -> action.call(p1.key, p1.value) }) -} - -/** - * 对给定的映射执行指定的操作,仅处理键和值。 - * 如果操作返回 true,则提前终止遍历。 - * - * @param map 要遍历的映射 - * @param action 要对每个键值对执行的操作,接收键和值作为参数,返回 Boolean 表示是否提前终止 - * @param 键的类型 - * @param 值的类型 - * @param 映射的具体类型 - */ -fun > forEachMapB( - map: A, action: P2RFunction, -) { - forEachB(map.entries, P1RFunction, Boolean> { p1 -> action.call(p1.key, p1.value) }) -} diff --git a/src/main/kotlin/com/mingliqiye/utils/system/SystemUtil.kt b/src/main/kotlin/com/mingliqiye/utils/system/SystemUtil.kt index 4e70237..c5a4c5b 100644 --- a/src/main/kotlin/com/mingliqiye/utils/system/SystemUtil.kt +++ b/src/main/kotlin/com/mingliqiye/utils/system/SystemUtil.kt @@ -16,7 +16,7 @@ * ProjectName mingli-utils * ModuleName mingli-utils.main * CurrentFile SystemUtil.kt - * LastUpdate 2026-10-28 22:43:54 + * LastUpdate 2026-11-23 07:50:35 * UpdateUser MingLiPro */ @file:JvmName("SystemUtils") @@ -264,7 +264,7 @@ val isNotJswarMode: Boolean get() = protocol != "jswar" /** * 当前操作系统的行分隔符 */ -val lineSeparator +val lineSeparator: String get() = System.lineSeparator() /** diff --git a/src/main/kotlin/com/mingliqiye/utils/thread/GlobalThreadPool.kt b/src/main/kotlin/com/mingliqiye/utils/thread/GlobalThreadPool.kt index b2ded0c..35b4f4e 100644 --- a/src/main/kotlin/com/mingliqiye/utils/thread/GlobalThreadPool.kt +++ b/src/main/kotlin/com/mingliqiye/utils/thread/GlobalThreadPool.kt @@ -16,57 +16,204 @@ * ProjectName mingli-utils * ModuleName mingli-utils.main * CurrentFile GlobalThreadPool.kt - * LastUpdate 2026-10-19 20:51:35 + * LastUpdate 2026-11-23 09:48:34 * UpdateUser MingLiPro */ package com.mingliqiye.utils.thread -import com.mingliqiye.utils.netty.NamedThreadFactory +import com.mingliqiye.utils.logger.MingLiLoggerFactory 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 +import com.mingliqiye.utils.thread.GlobalThreadPool.SHUTDOWN_HOOK_TIMEOUT_SECONDS +import com.mingliqiye.utils.thread.GlobalThreadPool.cpu +import com.mingliqiye.utils.thread.GlobalThreadPool.cpuDispatcher +import com.mingliqiye.utils.thread.GlobalThreadPool.io +import com.mingliqiye.utils.thread.GlobalThreadPool.ioDispatcher +import com.mingliqiye.utils.thread.GlobalThreadPool.main +import com.mingliqiye.utils.thread.GlobalThreadPool.mainDispatcher +import com.mingliqiye.utils.thread.GlobalThreadPool.pools +import com.mingliqiye.utils.thread.GlobalThreadPool.scheduled +import com.mingliqiye.utils.thread.GlobalThreadPool.shutdownAll +import com.mingliqiye.utils.thread.GlobalThreadPool.submit +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.asCoroutineDispatcher +import java.util.concurrent.* +import java.util.concurrent.atomic.AtomicBoolean /** - * 全局线程池,按任务类型提供三类共享池,通过 `by lazy` 懒加载。 + * 全局共享线程池,按负载类型划分,并额外提供协程调度器的统一入口。 + * + * | 池 | 线程数 | 队列 | 适用场景 | + * | :--- | :--- | :--- | :--- | + * | [main] | 核数 / 2 ~ 核数 | 128 有界 | 通用异步任务 | + * | [io] | 核数 x2 ~ 核数 x4 | 1024 有界 | 网络、磁盘等阻塞任务 | + * | [cpu] | 核数 | 无界 | 纯计算任务 | + * | [scheduled] | 核数 / 2(至少 1) | 延迟队列 | 延迟与周期任务 | + * + * 所有池的线程均为守护线程,不会阻止 JVM 退出;需要主动释放时调用 [shutdownAll], + * 进程正常退出时也会通过注册的关闭钩子自动调用一次(最多等 5 秒,超时强制关闭)。 + * 各池都是懒加载的,首次访问时才创建。 + * + * 协程调度器([mainDispatcher]、[ioDispatcher]、[cpuDispatcher])与池的对应关系并不统一: + * [mainDispatcher] 和 [ioDispatcher] 直接复用 kotlinx-coroutines 的共享调度器 + * (`asCoroutineDispatcher()` 会把每个续体变成一次线程池入队,高频调度下比 + * [Dispatchers.Default] 慢数倍);只有 [cpuDispatcher] 绑定 [cpu] 池——计算任务粒度大、 + * 续体切换少,入队开销可以忽略,换来独立的计算线程与可辨识的线程名。 + * 线程池也仍然直接面向 ExecutorService / Future / 阻塞任务等场景。 * * ```kotlin * GlobalThreadPool.io.execute { download() } * val result = GlobalThreadPool.cpu.submit { compute() }.get() - * runAsync { log("done") } + * GlobalThreadPool.runAsync { log("done") } * ``` */ object GlobalThreadPool { - /** IO 密集型全局池:线程多、队列有界,适合网络/磁盘等阻塞任务 */ - val io: ThreadPoolExecutor by lazy { - threadPool("MingLiGlobalIO") { - corePoolSize = availableProcessors * 2 - maximumPoolSize = availableProcessors * 4 - boundedQueue(1024) + private val log = MingLiLoggerFactory.getLogger() + + init { + registerShutdownHook() + } + + /** JVM 关闭时为在途任务保留的收尾时长(秒) */ + private const val SHUTDOWN_HOOK_TIMEOUT_SECONDS = 5L + + /** 可用处理器数,所有池的线程规模都由它推算 */ + private val cores: Int = availableProcessors + + /** + * 全局池拒绝策略:队列满时由提交线程执行,形成背压; + * 池已关闭时抛出 [RejectedExecutionException] 而不是静默丢弃, + * 避免 [submit] 返回一个永远不会完成的 [Future]。 + */ + private val globalRejectedHandler = RejectedExecutionHandler { runnable, executor -> + if (executor.isShutdown) { + log.debug("全局池已关闭,拒绝任务提交") + throw RejectedExecutionException("global thread pool is shutdown") + } + log.debug("全局池队列已满,任务改由提交线程 [{}] 执行", Thread.currentThread().name) + runnable.run() + } + + /** + * 通用全局池:适合短小的异步任务。 + * + * 队列满时由提交线程直接执行,形成天然背压、不丢任务; + * 池关闭后提交会抛出 [RejectedExecutionException]。 + */ + @JvmStatic + @get:JvmName("main") + val main: ThreadPoolExecutor by lazy { + val corePoolSize = (cores / 2).coerceAtLeast(1) + log.debug("初始化全局池 [main]: core={}, max={}, queue=128, daemon=true", corePoolSize, cores) + threadPool("MingLiGlobalMain") { + this.corePoolSize = corePoolSize + maximumPoolSize = cores + boundedQueue(128) allowCoreThreadTimeout = true daemon = true + rejectedHandler = globalRejectedHandler } } - /** CPU 密集型全局池:线程数等于核数,适合纯计算任务 */ + /** + * IO 密集型全局池:线程较多、队列有界,适合网络、磁盘等阻塞任务。 + * + * 核心线程允许空闲超时回收,空闲一段时间后会释放线程资源。 + */ + @JvmStatic + @get:JvmName("io") + val io: ThreadPoolExecutor by lazy { + val corePoolSize = cores * 2 + log.debug("初始化全局池 [io]: core={}, max={}, queue=1024, daemon=true", corePoolSize, cores * 4) + ioThreadPool("MingLiGlobalIO", daemon = true, rejectedHandler = globalRejectedHandler) + } + + /** + * CPU 密集型全局池:线程数等于核数,适合纯计算任务。 + * + * 队列无界,突发任务不会被拒绝,但提交速度长期超过消费速度时会持续积压。 + */ + @JvmStatic + @get:JvmName("cpu") val cpu: ThreadPoolExecutor by lazy { - threadPool("MingLiGlobalCPU") { - corePoolSize = availableProcessors - maximumPoolSize = availableProcessors - daemon = true + log.debug("初始化全局池 [cpu]: core={}, max={}, queue=unbounded, daemon=true", cores, cores) + cpuThreadPool("MingLiGlobalCPU", daemon = true, rejectedHandler = globalRejectedHandler) + } + + /** + * 全局定时池:承载 [delayRun]、[scheduleWithFixedDelay]、[scheduleAtFixedRate] 等定时任务。 + * + * 已取消的任务会立即移出队列([ScheduledThreadPoolExecutor.getRemoveOnCancelPolicy]), + * 关闭时丢弃尚未到期的延迟任务,避免 [shutdownAll] 被长延时任务拖住。 + */ + @JvmStatic + @get:JvmName("scheduled") + val scheduled: ScheduledThreadPoolExecutor by lazy { + val coreSize = (cores / 2).coerceAtLeast(1) + log.debug("初始化全局池 [scheduled]: core={}, daemon=true, removeOnCancelPolicy=true", coreSize) + scheduledThreadPool( + coreSize = coreSize, + name = "MingLiGlobalScheduled", + daemon = true, + ).apply { + removeOnCancelPolicy = true + executeExistingDelayedTasksAfterShutdownPolicy = false + continueExistingPeriodicTasksAfterShutdownPolicy = false } } - /** 全局定时任务池 */ - val scheduled: ScheduledThreadPoolExecutor by lazy { - // 包装一层将定时线程设为守护线程,避免阻塞 JVM 退出 - val base = NamedThreadFactory.of("MingLiGlobalScheduled") - ScheduledThreadPoolExecutor( - (availableProcessors / 2).coerceAtLeast(1), - ) { runnable -> base.newThread(runnable).apply { isDaemon = true } } + // ---- 协程调度器 ---- + + /** + * 通用协程调度器:[Dispatchers.Default] 的命名视图。 + * + * 它不包装 [main] 线程池,而是直接使用 kotlinx-coroutines 的共享调度器 + * (每个 worker 本地队列 + work-stealing),避免"每个续体一次线程池入队"的开销。 + * 并行度取 `max(4, CPU 核数)`;等于或大于 Default 核心池时只是命名视图,不做额外限流。 + * + * 共享实例,不要 `close()`;它不归 [shutdownAll] 管。 + */ + @JvmStatic + @get:JvmName("mainDispatcher") + val mainDispatcher: CoroutineDispatcher by lazy { + val parallelism = cores.coerceAtLeast(4) + log.debug("初始化协程调度器 [mainDispatcher]: Dispatchers.Default, parallelism={}", parallelism) + Dispatchers.Default.limitedParallelism(parallelism, "MingLiGlobalMainDispatcher") + } + + /** + * IO 密集型协程调度器:[Dispatchers.IO] 的命名限流视图,最大并发取 `max(128, CPU 核数)`。 + * + * 底层仍是 IO 的弹性调度器;套一层 `limitedParallelism` 是为了给并发线程数一个 + * 明确上限,代价是每次分发多一层原子计数。 + * + * 共享实例,不要 `close()`;它不归 [shutdownAll] 管。 + */ + @JvmStatic + @get:JvmName("ioDispatcher") + val ioDispatcher: CoroutineDispatcher by lazy { + val parallelism = 128.coerceAtLeast(cores) + log.debug("初始化协程调度器 [ioDispatcher]: Dispatchers.IO, parallelism={}", parallelism) + Dispatchers.IO.limitedParallelism(parallelism, "MingLiGlobalIODispatcher") + } + + /** + * 计算专用的协程调度器:绑定独立的 [cpu] 池,线程数等于 CPU 核数, + * 线程名为 `MingLiGlobalCPU-*`。 + * + * 这里刻意不复用 [Dispatchers.Default]:计算任务粒度大、续体切换少,每次入队的那点 + * 开销可以忽略,换来的是与全局 Default 调度器隔离的独立计算线程,以及随 + * [shutdownAll] 一起关闭(关闭后投递的协程会被取消并转到 IO 清理)。 + * + * 只用于 CPU 密集型计算,不要在里面做阻塞调用。 + */ + @JvmStatic + @get:JvmName("cpuDispatcher") + val cpuDispatcher: CoroutineDispatcher by lazy { + log.debug("初始化协程调度器 [cpuDispatcher]: 绑定全局池 [cpu]") + cpu.asCoroutineDispatcher() } // ---- 便捷提交 ---- @@ -110,40 +257,191 @@ object GlobalThreadPool { @JvmStatic fun submit(runnable: Runnable, result: T): Future = io.submit(runnable, result) + // ---- 便捷任务 ---- + /** - * 优雅关闭全部线程池(先正常关闭,超时后强制关闭) + * 向全局 IO 池提交无返回值任务 + * + * Kotlin 可直接用 lambda,Java 也可直接传 `Runnable`。 + * + * @param block 要执行的任务 + * @return 任务句柄,可用于等待完成或取消 */ @JvmStatic - fun shutdownAll() { - io.shutdownGracefully() - cpu.shutdownGracefully() - scheduled.shutdownGracefully() + fun runAsync(block: Runnable): Future<*> = io.submit(block) + + /** + * 向全局 IO 池提交带返回值任务 + * + * Kotlin 可直接用 lambda,Java 也可直接传 `Callable`。 + * + * @param T 任务返回值类型 + * @param block 要执行的任务 + * @return 任务句柄,可通过 [Future.get] 获取结果 + */ + @JvmStatic + fun callAsync(block: Callable): Future = io.submit(block) + + /** + * 向全局 CPU 池提交计算任务 + * + * Kotlin 可直接用 lambda,Java 也可直接传 `Callable`。 + * + * @param T 任务返回值类型 + * @param block 要执行的计算任务 + * @return 任务句柄,可通过 [Future.get] 获取结果 + */ + @JvmStatic + fun computeAsync(block: Callable): Future = cpu.submit(block) + + /** + * 在全局 IO 池执行任务并阻塞等待完成 + * + * @param block 要执行的任务 + */ + @JvmStatic + fun runAsyncAwait(block: Runnable) { + io.submit(block).get() } + + /** + * 在全局 IO 池执行任务并阻塞等待结果 + * + * @param T 任务返回值类型 + * @param block 要执行的任务 + * @return 任务执行结果 + */ + @JvmStatic + fun callAsyncAwait(block: Callable): T = io.submit(block).get() + + // ---- 监控 ---- + + /** + * 全部全局池,按名称索引,便于统一监控、上报或统计。 + * + * 键依次为 `main`、`io`、`cpu`、`scheduled`,值复用同一批单例。 + * 每次调用返回新的只读视图;访问会初始化尚未创建的全局池。 + */ + @JvmStatic + fun pools(): Map = executorPools() + + /** + * 采集全部全局池的运行快照,键与 [pools] 一致。 + * + * 适合周期性上报指标,例如: + * + * ```kotlin + * GlobalThreadPool.snapshotAll().forEach { (name, snapshot) -> + * log.info("pool {}: {}", name, snapshot) + * } + * ``` + * + * @return 池名称到 [ThreadPoolSnapshot] 的映射 + */ + @JvmStatic + fun snapshotAll(): Map = + executorPools().mapValues { (_, pool) -> pool.snapshot() } + + // ---- 生命周期 ---- + + private val shutdownState = AtomicBoolean(false) + + /** + * 是否已经调用过 [shutdownAll] + */ + @JvmStatic + val isShutdown: Boolean get() = shutdownState.get() + + /** + * 优雅关闭全部全局池。 + * + * 先停止接收新任务,再在统一的截止时间内等待线程池终止; + * 到期仍未结束的池会被 [ExecutorService.shutdownNow] 强制关闭。 + * 全局池关闭后不可复用,重复调用直接返回 `true`; + * 之后再提交任务会抛出 [RejectedExecutionException]。 + * + * @param timeout 整体等待时长,从开始关闭时计时,所有池共享 + * @param unit 时间单位 + * @return 是否所有池都在截止时间内正常终止 + */ + @JvmStatic + @JvmOverloads + fun shutdownAll(timeout: Long = 30, unit: TimeUnit = TimeUnit.SECONDS): Boolean { + if (!shutdownState.compareAndSet(false, true)) { + log.debug("全局线程池已关闭,忽略重复的 shutdownAll 调用") + return true + } + val startNanos = System.nanoTime() + val pools = executorPools() + log.debug("正在关闭全局线程池: {},等待上限 {} {}", pools.keys, timeout, unit) + val deadline = startNanos + unit.toNanos(timeout) + pools.values.forEach { it.shutdown() } + var terminated = true + try { + for ((name, pool) in pools) { + val remaining = deadline - System.nanoTime() + val done = remaining > 0 && pool.awaitTermination(remaining, TimeUnit.NANOSECONDS) + if (done) { + log.debug("线程池 [{}] 已关闭,完成任务数={}", name, pool.completedTaskCount) + } else { + terminated = false + log.warn("线程池 [{}] 未在期限内终止,执行 shutdownNow()", name) + pool.shutdownNow() + } + } + } catch (_: InterruptedException) { + // 保留中断状态,并强制关闭剩余池 + Thread.currentThread().interrupt() + log.warn("等待全局线程池关闭时线程被中断,强制关闭剩余线程池") + pools.values.forEach { it.shutdownNow() } + terminated = false + } + val elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNanos) + if (terminated) { + log.debug("全局线程池关闭完成,耗时 {} ms", elapsedMillis) + } else { + log.warn("全局线程池关闭完成,但存在未正常终止的池,耗时 {} ms", elapsedMillis) + } + return terminated + } + + /** + * 注册 JVM 关闭钩子:进程退出前调用 [shutdownAll],给在途任务一段收尾时间。 + * + * 池线程都是守护线程,不注册钩子 JVM 也能正常退出;钩子的意义是把"直接中断" + * 变成"最多等 [SHUTDOWN_HOOK_TIMEOUT_SECONDS] 秒再强制关闭"。 + * JVM 已在关闭中(例如本对象是在别的 shutdown hook 里第一次被访问)或安全管理器 + * 拒绝注册时静默跳过,不影响全局池继续使用。 + */ + private fun registerShutdownHook() { + val hook = Thread({ + try { + log.debug("JVM 关闭钩子触发,开始关闭全局线程池") + shutdownAll(SHUTDOWN_HOOK_TIMEOUT_SECONDS, TimeUnit.SECONDS) + } catch (t: Throwable) { + // 日志框架可能已先于本钩子关闭,这里也不能让异常阻塞 JVM 退出 + runCatching { log.warn("JVM 关闭钩子中关闭全局线程池失败", t) } + } + }, "MingLiGlobalPool-Shutdown") + try { + Runtime.getRuntime().addShutdownHook(hook) + log.debug("已注册 JVM 关闭钩子: {}", hook.name) + } catch (_: IllegalStateException) { + // JVM 已在关闭中,无法再注册钩子 + log.debug("JVM 已在关闭中,跳过注册关闭钩子") + } catch (_: SecurityException) { + // 安全管理器拒绝注册钩子 + log.debug("安全管理器拒绝注册关闭钩子,跳过") + } + } + + /** + * 全部全局池的有序视图,键为池名称 + */ + private fun executorPools(): Map = linkedMapOf( + "main" to main, + "io" to io, + "cpu" to cpu, + "scheduled" to scheduled, + ) } - -/** - * 向全局 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/SuspendUtils.kt b/src/main/kotlin/com/mingliqiye/utils/thread/SuspendUtils.kt new file mode 100644 index 0000000..03bd810 --- /dev/null +++ b/src/main/kotlin/com/mingliqiye/utils/thread/SuspendUtils.kt @@ -0,0 +1,71 @@ +/* + * 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 SuspendUtils.kt + * LastUpdate 2026-11-23 09:14:46 + * UpdateUser MingLiPro + */ + +package com.mingliqiye.utils.suspend + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.withContext +import kotlin.contracts.ExperimentalContracts +import kotlin.contracts.InvocationKind +import kotlin.contracts.contract +import kotlin.coroutines.CoroutineContext + + +@OptIn(ExperimentalContracts::class) +suspend inline fun CoroutineContext.withContext(noinline block: suspend CoroutineScope.() -> T): T { + contract { + callsInPlace(block, InvocationKind.EXACTLY_ONCE) + } + return withContext(this) { + block(this) + } +} + +fun T.asCompletableDeferred() = CompletableDeferred(this) + + +@OptIn(ExperimentalContracts::class) +fun CoroutineContext.runBlocking(block: suspend CoroutineScope.() -> T): T { + contract { + callsInPlace(block, InvocationKind.EXACTLY_ONCE) + } + return kotlinx.coroutines.runBlocking(this) { + block() + } +} + +/** + * 在当前线程上阻塞运行协程,等价于 [kotlinx.coroutines.runBlocking]。 + * + * 使用调用线程自己的事件循环,不占用 [com.mingliqiye.utils.thread.GlobalThreadPool] 的池线程, + * 因此不会被池的并发度限制或关闭影响;需要在本线程之外执行时用 [CoroutineContext.runBlocking]。 + */ +@OptIn(ExperimentalContracts::class) +fun runBlocking(block: suspend CoroutineScope.() -> T): T { + contract { + callsInPlace(block, InvocationKind.EXACTLY_ONCE) + } + return kotlinx.coroutines.runBlocking { + block() + } +} diff --git a/src/main/kotlin/com/mingliqiye/utils/thread/ThreadExt.kt b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadExt.kt index 243ef9c..720cd0f 100644 --- a/src/main/kotlin/com/mingliqiye/utils/thread/ThreadExt.kt +++ b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadExt.kt @@ -16,7 +16,7 @@ * ProjectName mingli-utils * ModuleName mingli-utils.main * CurrentFile ThreadExt.kt - * LastUpdate 2026-10-19 20:51:35 + * LastUpdate 2026-11-23 07:50:35 * UpdateUser MingLiPro */ @@ -69,7 +69,7 @@ fun Runnable.asThread( * ``` */ fun Thread.onUncaught(action: (Thread, Throwable) -> Unit): Thread = apply { - setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler { t, e -> action(t, e) }) + setUncaughtExceptionHandler { t, e -> action(t, e) } } /** diff --git a/src/main/kotlin/com/mingliqiye/utils/thread/ThreadPoolBuilder.kt b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadPoolBuilder.kt index 59e0e16..2b45995 100644 --- a/src/main/kotlin/com/mingliqiye/utils/thread/ThreadPoolBuilder.kt +++ b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadPoolBuilder.kt @@ -16,7 +16,7 @@ * ProjectName mingli-utils * ModuleName mingli-utils.main * CurrentFile ThreadPoolBuilder.kt - * LastUpdate 2026-10-19 20:51:35 + * LastUpdate 2026-11-23 09:31:23 * UpdateUser MingLiPro */ @@ -114,21 +114,9 @@ class ThreadPoolBuilder internal constructor() { * @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 + val factory = threadFactory + ?.let { decorateThreadFactory(it, daemon, priority, uncaughtHandler) } + ?: namedThreadFactory(name, daemon, priority, uncaughtHandler) return ThreadPoolExecutor( corePoolSize, maximumPoolSize, @@ -143,6 +131,51 @@ class ThreadPoolBuilder internal constructor() { } } +/** + * 创建带名称的线程工厂,可选配置守护线程、优先级与未捕获异常处理器。 + * + * 适合与 JDK 原生线程池(如 [ScheduledThreadPoolExecutor])搭配使用: + * + * ```kotlin + * val scheduler = ScheduledThreadPoolExecutor(1, namedThreadFactory("scheduler", daemon = true)) + * ``` + * + * @param name 线程名称前缀,实际线程名为 `name-1`、`name-2` ... + * @param daemon 是否创建守护线程 + * @param priority 线程优先级 + * @param uncaughtHandler 未捕获异常处理器,为 null 时使用线程默认处理器 + */ +@JvmOverloads +fun namedThreadFactory( + name: String = "MingLiPool", + daemon: Boolean = false, + priority: Int = Thread.NORM_PRIORITY, + uncaughtHandler: Thread.UncaughtExceptionHandler? = null, +): ThreadFactory = decorateThreadFactory( + NamedThreadFactory.of(name), + daemon, + priority, + uncaughtHandler, +) + +/** + * 按需装饰线程工厂:需要定制守护线程、优先级或异常处理器时包一层,否则原样返回。 + */ +private fun decorateThreadFactory( + base: ThreadFactory, + daemon: Boolean, + priority: Int, + uncaughtHandler: Thread.UncaughtExceptionHandler?, +): ThreadFactory = if (daemon || priority != Thread.NORM_PRIORITY || uncaughtHandler != null) { + ThreadFactory { runnable -> + base.newThread(runnable).apply { + isDaemon = daemon + this.priority = priority + uncaughtHandler?.let { setUncaughtExceptionHandler(it) } + } + } +} else base + /** * 以 DSL 方式构建线程池 * @@ -195,22 +228,45 @@ fun cachedThreadPool(name: String = "MingLiCachedPool"): ThreadPoolExecutor = /** * 创建 IO 密集型线程池:更多线程 + 有界队列 + * + * @param name 线程池名称 + * @param daemon 线程是否为守护线程 + * @param rejectedHandler 任务拒绝策略,默认为由提交线程执行 */ -fun ioThreadPool(name: String = "MingLiIoPool"): ThreadPoolExecutor = +@JvmOverloads +fun ioThreadPool( + name: String = "MingLiIoPool", + daemon: Boolean = false, + rejectedHandler: RejectedExecutionHandler = ThreadPoolExecutor.CallerRunsPolicy(), + corePoolSize: Int = availableProcessors * 2, +): ThreadPoolExecutor = threadPool(name) { - corePoolSize = availableProcessors * 2 + this.corePoolSize = corePoolSize maximumPoolSize = availableProcessors * 4 boundedQueue(1024) allowCoreThreadTimeout = true + this.daemon = daemon + this.rejectedHandler = rejectedHandler } /** * 创建 CPU 密集型线程池:线程数等于核数,避免上下文切换开销 + * + * @param name 线程池名称 + * @param daemon 线程是否为守护线程 + * @param rejectedHandler 任务拒绝策略,默认为由提交线程执行 */ -fun cpuThreadPool(name: String = "MingLiCpuPool"): ThreadPoolExecutor = +@JvmOverloads +fun cpuThreadPool( + name: String = "MingLiCpuPool", + daemon: Boolean = false, + rejectedHandler: RejectedExecutionHandler = ThreadPoolExecutor.CallerRunsPolicy(), +): ThreadPoolExecutor = threadPool(name) { corePoolSize = availableProcessors maximumPoolSize = availableProcessors + this.daemon = daemon + this.rejectedHandler = rejectedHandler } /** @@ -218,9 +274,12 @@ fun cpuThreadPool(name: String = "MingLiCpuPool"): ThreadPoolExecutor = * * @param coreSize 核心线程数,默认 CPU 核数 / 2(至少 1) * @param name 线程池名称 + * @param daemon 线程是否为守护线程 */ +@JvmOverloads fun scheduledThreadPool( coreSize: Int = (availableProcessors / 2).coerceAtLeast(1), name: String = "MingLiScheduledPool", + daemon: Boolean = false, ): ScheduledThreadPoolExecutor = - ScheduledThreadPoolExecutor(coreSize, NamedThreadFactory.of(name)) + ScheduledThreadPoolExecutor(coreSize, namedThreadFactory(name, daemon = daemon)) diff --git a/src/main/kotlin/com/mingliqiye/utils/thread/ThreadUtils.kt b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadUtils.kt index f67a591..a92fb8e 100644 --- a/src/main/kotlin/com/mingliqiye/utils/thread/ThreadUtils.kt +++ b/src/main/kotlin/com/mingliqiye/utils/thread/ThreadUtils.kt @@ -16,7 +16,7 @@ * ProjectName mingli-utils * ModuleName mingli-utils.main * CurrentFile ThreadUtils.kt - * LastUpdate 2026-02-09 20:14:22 + * LastUpdate 2026-11-22 10:03:03 * UpdateUser MingLiPro */ @@ -134,4 +134,5 @@ object ThreadUtils { append("\n\n") } } + } diff --git a/src/test/kotlin/com/mingliqiye/utils/suspend/SuspendUtilsTest.kt b/src/test/kotlin/com/mingliqiye/utils/suspend/SuspendUtilsTest.kt new file mode 100644 index 0000000..7ce84d9 --- /dev/null +++ b/src/test/kotlin/com/mingliqiye/utils/suspend/SuspendUtilsTest.kt @@ -0,0 +1,62 @@ +/* + * 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 SuspendUtilsTest.kt + * LastUpdate 2026-11-23 09:14:46 + * UpdateUser MingLiPro + */ + +package com.mingliqiye.utils.suspend + +import com.mingliqiye.utils.thread.GlobalThreadPool +import kotlinx.coroutines.delay +import org.junit.jupiter.api.Assertions.assertNotEquals +import org.junit.jupiter.api.Assertions.assertSame +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import java.util.concurrent.TimeUnit + +/** + * SuspendUtils 协程工具与 [GlobalThreadPool] 调度器的集成测试 + */ +class SuspendUtilsTest { + + /** 测试 CoroutineContext.runBlocking 使用接收者上下文执行协程 */ + @Test + fun testContextRunBlockingUsesReceiverContext() { + val caller = Thread.currentThread() + val worker = GlobalThreadPool.ioDispatcher.runBlocking { Thread.currentThread() } + assertNotEquals(caller, worker, "receiver context was ignored") + } + + /** 测试顶层 runBlocking 使用调用线程的事件循环,不占用全局线程池 */ + @Test + fun testRunBlockingRunsOnCallerThread() { + val caller = Thread.currentThread() + val thread = com.mingliqiye.utils.suspend.runBlocking { Thread.currentThread() } + assertSame(caller, thread) + } + + /** 测试 runBlocking 内挂起(delay)后仍能按时恢复 */ + @Test + fun testRunBlockingSupportsDelay() { + val start = System.nanoTime() + com.mingliqiye.utils.suspend.runBlocking { delay(100) } + val elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start) + assertTrue(elapsedMillis >= 90, "delay resumed too early: ${elapsedMillis}ms") + } +} diff --git a/src/test/kotlin/com/mingliqiye/utils/thread/AsyncTasksTest.kt b/src/test/kotlin/com/mingliqiye/utils/thread/AsyncTasksTest.kt index c5bd776..8146feb 100644 --- a/src/test/kotlin/com/mingliqiye/utils/thread/AsyncTasksTest.kt +++ b/src/test/kotlin/com/mingliqiye/utils/thread/AsyncTasksTest.kt @@ -16,14 +16,21 @@ * ProjectName mingli-utils * ModuleName mingli-utils.test * CurrentFile AsyncTasksTest.kt - * LastUpdate 2026-10-19 20:58:00 + * LastUpdate 2026-11-23 09:45:49 * UpdateUser MingLiPro */ package com.mingliqiye.utils.thread +import kotlinx.coroutines.ExecutorCoroutineDispatcher +import kotlinx.coroutines.delay +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withContext import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertNotEquals import org.junit.jupiter.api.Assertions.assertNull +import org.junit.jupiter.api.Assertions.assertSame import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test @@ -254,44 +261,99 @@ class AsyncTasksTest { // ---- GlobalThreadPool ---- - /** 测试 GlobalThreadPool 的 io/cpu/scheduled 全局线程池已正确初始化 */ + /** 测试 GlobalThreadPool 的 main/io/cpu/scheduled 全局线程池已正确初始化 */ @Test fun testGlobalPools() { + assertFalse(GlobalThreadPool.isShutdown) + assertTrue(GlobalThreadPool.main.corePoolSize > 0) assertTrue(GlobalThreadPool.io.corePoolSize > 0) assertTrue(GlobalThreadPool.cpu.corePoolSize > 0) assertTrue(GlobalThreadPool.scheduled.corePoolSize > 0) } + /** 测试全局池注册表与批量快照的名称、顺序一致 */ + @Test + fun testGlobalPoolRegistry() { + val pools = GlobalThreadPool.pools() + assertEquals(listOf("main", "io", "cpu", "scheduled"), pools.keys.toList()) + val snapshots = GlobalThreadPool.snapshotAll() + assertEquals(pools.keys.toList(), snapshots.keys.toList()) + assertTrue(snapshots.getValue("io").maximumPoolSize > 0) + } + + /** 测试全局池的工作线程为守护线程,不会阻止 JVM 退出 */ + @Test + fun testGlobalPoolThreadsAreDaemon() { + val daemon = GlobalThreadPool.callAsync { Thread.currentThread().isDaemon }.get(5, TimeUnit.SECONDS) + assertTrue(daemon) + } + + /** 测试 mainDispatcher 复用 Dispatchers.Default,而不是 main 线程池 */ + @Test + fun testMainDispatcher() = runBlocking { + val caller = Thread.currentThread() + val thread = withContext(GlobalThreadPool.mainDispatcher) { Thread.currentThread() } + assertNotEquals(caller, thread) + assertTrue(thread.name.startsWith("DefaultDispatcher-worker"), "unexpected thread: ${thread.name}") + assertTrue(thread.isDaemon) + } + + /** 测试 dispatcher 映射:main/io 是共享调度器的命名限流视图,cpu 绑定 cpu 池 */ + @Test + fun testDispatchersMapping() { + assertEquals("MingLiGlobalMainDispatcher", GlobalThreadPool.mainDispatcher.toString()) + assertEquals("MingLiGlobalIODispatcher", GlobalThreadPool.ioDispatcher.toString()) + val cpuExecutor = (GlobalThreadPool.cpuDispatcher as? ExecutorCoroutineDispatcher)?.executor + assertSame(GlobalThreadPool.cpu, cpuExecutor) + } + + /** 测试 cpuDispatcher 在 MingLiGlobalCPU 的守护线程上执行 */ + @Test + fun testCpuDispatcher() = runBlocking { + val thread = withContext(GlobalThreadPool.cpuDispatcher) { Thread.currentThread() } + assertTrue(thread.name.startsWith("MingLiGlobalCPU"), "unexpected thread: ${thread.name}") + assertTrue(thread.isDaemon) + } + + /** 测试 ioDispatcher 上的 delay 悬起后仍能按时恢复 */ + @Test + fun testIoDispatcherDelay() = runBlocking { + val start = System.nanoTime() + withContext(GlobalThreadPool.ioDispatcher) { delay(100) } + val elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start) + assertTrue(elapsedMillis >= 90, "delay resumed too early: ${elapsedMillis}ms") + } + /** 测试 runAsync 异步执行无返回值任务 */ @Test fun testRunAsync() { - assertNull(runAsync { }.get(5, TimeUnit.SECONDS)) + assertNull(GlobalThreadPool.runAsync { }.get(5, TimeUnit.SECONDS)) } /** 测试 callAsync 在 IO 线程池异步执行并返回结果 */ @Test fun testCallAsync() { - assertEquals("io", callAsync { "io" }.get(5, TimeUnit.SECONDS)) + assertEquals("io", GlobalThreadPool.callAsync { "io" }.get(5, TimeUnit.SECONDS)) } /** 测试 computeAsync 在 CPU 线程池异步计算并返回结果 */ @Test fun testComputeAsync() { - assertEquals(4, computeAsync { 2 + 2 }.get(5, TimeUnit.SECONDS)) + assertEquals(4, GlobalThreadPool.computeAsync { 2 + 2 }.get(5, TimeUnit.SECONDS)) } /** 测试 runAsyncAwait 异步执行并阻塞等待完成 */ @Test fun testRunAsyncAwait() { val counter = AtomicInteger() - runAsyncAwait { counter.incrementAndGet() } + GlobalThreadPool.runAsyncAwait { counter.incrementAndGet() } assertEquals(1, counter.get()) } /** 测试 callAsyncAwait 异步执行并阻塞等待返回结果 */ @Test fun testCallAsyncAwait() { - assertEquals("await", callAsyncAwait { "await" }) + assertEquals("await", GlobalThreadPool.callAsyncAwait { "await" }) } /** 测试 GlobalThreadPool.execute 提交任务并被执行 */