英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论