可以在Kotlin Multiplatform的commonMain代码中使用@Synchronized注解吗?

huangapple go评论63阅读模式
英文:

Can I use @Synchronized annotation in Kotlin Multiplatform commonMain code?

问题

@Synchronized 注解可以在 Kotlin Multiplatform 的 commonMain 代码中使用吗?
该库仅针对 JVM 和 JS。

它会对调用来自该库的 commonMain 代码的 Kotlin/JS 应用程序产生影响吗?

当我在 commonMain 中使用 @Synchronized 时,IntelliJ 显示它是从 kotlin-stdlib-common 导入的;在 jsMain 中,它显示从 kotlin-stdlib-js 导入;然而,在这两种情况下,导入语句仍然是 import kotlin.jvm.Synchronized

英文:

Can @Synchronized annotation be used in common code (commonMain) code of Kotlin Multiplatform?
The library only targets JVM and JS.

Will it have any impact on a Kotlin/JS application that calls the commonMain code from this library?

When I use @Synchronized in commonMain, Intellij shows it is imported from import kotlin-stdlib-common; in jsMain, it shows imported from kotlin-stdlib-js; however, in both the cases, the import statement remains import kotlin.jvm.Synchronized

答案1

得分: 1

UPD:

kotlin.jvm.Volatile 注解已经在 Kotlin/JS 和 Kotlin/Native 中被弃用,自 Kotlin 1.9 版本开始出现警告。应改用 kotlin.concurrent.Volatile

文档所示,此注解仅对从 Kotlin 函数生成的 JVM 方法产生影响:

标记了从注解函数生成的 JVM 方法为synchronized,这意味着该方法将受到实例(或对于静态方法,类)的监视器保护,以防止多个线程的并发执行。

在标准库的 JS 部分的源代码中,您可以找到关于该注解(以及 @Volatile)的以下注释,这为其在 JVM 之外的状态提供了一些提示:

// 这些用于stdlib中的常见生成代码

// TODO:找到如何弃用这些

英文:

UPD:

The kotlin.jvm.Volatile annotation has been deprecated for Kotlin/JS and Kotlin/Native, with a warning since Kotlin 1.9. kotlin.concurrent.Volatile should be used instead.


As indicated in the documentation, this annotation will only have effect on the JVM method generated from the Kotlin function:

> Marks the JVM method generated from the annotated function as synchronized, meaning that the method will be protected from concurrent execution by multiple threads by the monitor of the instance (or, for static methods, the class) on which the method is defined.

In the sources of the JS part of the standard library, you can find the following comment about the annotation (along with @Volatile), which gives a small hint about its status outside of the JVM:

> // these are used in common generated code in stdlib
>
> // TODO: find how to deprecate these ones

huangapple
  • 本文由 发表于 2023年2月26日 23:14:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75572932.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定