Search code examples
kotlinsynchronizedkotlin-multiplatform

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


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


Solution

  • 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