Skip to content

Commit a32307f

Browse files
authored
Merge pull request #50 from ForteScarlet/pref-jvm-runtime
优化 `runtime` 中的 JVM 平台实现:异步调度器默认使用 `GlobalScope`
2 parents c70a2db + bc61583 commit a32307f

File tree

1 file changed

+16
-4
lines changed
  • runtime/suspend-transform-runtime/src/jvmMain/kotlin/love/forte/plugin/suspendtrans/runtime

1 file changed

+16
-4
lines changed

runtime/suspend-transform-runtime/src/jvmMain/kotlin/love/forte/plugin/suspendtrans/runtime/RunInSuspendJvm.kt

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,14 @@ public fun <T> `$runInBlocking$`(block: suspend () -> T): T = runBlocking(`$Coro
2727
private val classLoader: ClassLoader
2828
get() = Thread.currentThread().contextClassLoader ?: ClassLoader.getSystemClassLoader()
2929

30-
private val jdk8Support: Boolean
31-
get() = runCatching {
30+
// 现在是不是最低也是JDK8了?
31+
// 也许这个判断已经不需要了?
32+
private val jdk8Support: Boolean by lazy {
33+
runCatching {
3234
classLoader.loadClass("kotlinx.coroutines.future.FutureKt")
3335
true
3436
}.getOrElse { false }
37+
}
3538

3639
private interface FutureTransformer {
3740
fun <T> trans(scope: CoroutineScope, block: suspend () -> T): CompletableFuture<T>
@@ -67,17 +70,26 @@ private object SimpleTransformer : FutureTransformer {
6770
}
6871
}
6972

70-
private val transformer: FutureTransformer =
73+
private val transformer: FutureTransformer by lazy {
7174
if (jdk8Support) CoroutinesJdk8Transformer
7275
else SimpleTransformer
76+
}
7377

7478

79+
@OptIn(DelicateCoroutinesApi::class)
7580
@Deprecated("Just for generate.", level = DeprecationLevel.HIDDEN)
7681
@Suppress("FunctionName")
7782
public fun <T> `$runInAsync$`(
7883
block: suspend () -> T,
7984
scope: CoroutineScope? = null
80-
): CompletableFuture<T> = transformer.trans(scope ?: `$CoroutineScope4J$`, block)
85+
): CompletableFuture<T> =
86+
// 比起在内部构建一个使用 Dispatchers.IO、并且永不被关闭的 CoroutineScope,
87+
// 为何不直接使用 GlobalScope?
88+
// 作为作用域:它用不被关闭、无法被关闭
89+
// 作为异步调度器:它没必要使用IO
90+
// 而对于更加复杂的场景,也许需要考虑完全定制化,
91+
// 而不是使用当前这个简单的runtime包内的实现
92+
transformer.trans(scope ?: GlobalScope, block)
8193

8294

8395

0 commit comments

Comments
 (0)