12.1.5 编译器执行策略

原文链接: https://kotlinlang.org/docs/compiler-execution-strategy.html

12.1.5 编译器执行策略

Kotlin 编译器执行策略定义了 Kotlin 编译器在哪里运行。Gradle或 Maven这类构建工具会配置该策略。

有两种编译器执行策略:

| 策略 | Kotlin 编译器在哪里运行 | 其他特性与说明 |

| Kotlin 守护进程 | 在它自己的守护进程中 | 在 Gradle 和 Maven 中默认且最快的策略。守护进程可以在不同的构建系统进程和多个并行编译之间共享。 | | 进程内(In process) | 在构建工具的进程中 | 从内存管理的角度看是最简单的策略,但由于它与其他在同一进程中运行的逻辑共享状态(例如 JVM 系统属性),隔离性较差。 |

在 Gradle 中配置

你可以使用以下属性之一来定义 Kotlin 编译器执行策略:

  • kotlin.compiler.execution.strategy Gradle 属性。
  • compilerExecutionStrategy 编译任务属性。

使用 Gradle 属性

kotlin.compiler.execution.strategy 属性的可能取值为:

  • daemon(默认)
  • in-process

在 gradle.properties 中设置 kotlin.compiler.execution.strategy 属性:

kotlin.compiler.execution.strategy=in-process

使用编译任务属性

compilerExecutionStrategy 任务属性的优先级高于 kotlin.compiler.execution.strategy Gradle 属性。

compilerExecutionStrategy 任务属性的可能取值为:

在你的构建脚本中设置 compilerExecutionStrategy 任务属性:

Kotlin

1
2
3
4
5
6
7
8
import org.jetbrains.kotlin.gradle.tasks.CompileUsingKotlinDaemon
import org.jetbrains.kotlin.gradle.tasks.KotlinCompilerExecutionStrategy

// ...

tasks.withType<CompileUsingKotlinDaemon>().configureEach {
    compilerExecutionStrategy.set(KotlinCompilerExecutionStrategy.IN_PROCESS)
}

Groovy

1
2
3
4
5
6
7
8
9
import org.jetbrains.kotlin.gradle.tasks.CompileUsingKotlinDaemon
import org.jetbrains.kotlin.gradle.tasks.KotlinCompilerExecutionStrategy

// ...

tasks.withType(CompileUsingKotlinDaemon)
        .configureEach {
            compilerExecutionStrategy = KotlinCompilerExecutionStrategy.IN_PROCESS
        }

回退策略

如果与 Kotlin 守护进程的通信失败,编译器会回退到 “In process” 策略。

发生这种回退时,Gradle 会在构建输出中打印以下警告:

Failed to compile with Kotlin daemon: java.lang.RuntimeException: Could not connect to Kotlin compile daemon
[exception stacktrace]
Using fallback strategy: Compile without Kotlin daemon
Try ./gradlew --stop if this issue persists.

静默回退可能消耗大量系统资源,或导致构建结果不确定。更多信息请参阅这个 YouTrack 问题。

要阻止回退,请使用 kotlin.daemon.useFallbackStrategy Gradle 属性。它的默认值是 true。当设为 false 时,如果守护进程启动或通信出现问题,构建就会失败。请在 gradle.properties 中声明该属性:

kotlin.daemon.useFallbackStrategy=false

Kotlin 编译任务中还有一个 useDaemonFallbackStrategy 属性。如果你同时使用这两个属性,useDaemonFallbackStrategy 属性的优先级更高。

Kotlin

1
2
3
4
5
tasks {
    compileKotlin {
        useDaemonFallbackStrategy.set(false)
    }
}

Groovy

1
2
3
tasks.named("compileKotlin").configure {
    useDaemonFallbackStrategy = false
}

如果没有足够的内存来运行编译,日志中会显示相关消息。

在 Maven 中配置