Platform independence with common module & thread safety?


#1

Hi,
I’m rather new to Kotlin. I’m currently working on a platform-independant project, i.e. I’m using a common module and common-js/common-jvm implementations.

I have a class which can be called form multiple threads and has internal state (i.e. several maps).
I’d like to avoid to rewrite that for every target platform.

I can’t use an actor based model as coroutines-common only async/await as far as I can see. I also don’t see another way without adding some abstractions (which I’d like to avoid) to workaround this.
How is concurrency supposed to be handled in common modules?

Are there any recommendations?

Thanks!
Joachim


#2

The good way would be to use actors when they are available, of course. Meanwhile, you can write your common thread-safe classes using @Synchronized annotation and synchronized function from Kotlin stdlib. They are common, that is available under both Kotlin/JVM and Kotlin/JS. They don’t do anything (nop) under Kotlin/JS, but would compile to the corresponding JVM constructs on Kotlin/JVM.


#3

Thanks! I’m glad that actors for JS are planned :slight_smile:

Is it possible that the synchronized annotation is in stdlib and not in stdlib-common?
Using Kotlin 1.2.20 Gradle and IntelliJ are complaining and ‘kotlin.jvm.Synchronized’ is in kotlin-stdlib-1.2.20.jar.

I can use the synchronized function, though, as it seems.


#4

Sorry. My bad. @Synchronized is indeed unavailable on Kotlin/JS, but synchronized is.