10

What multiplatform Lock or synchronization approach should be used in multiplatform Kotlin code? Previously in Java code i used synchronized and i can see synchronized in Kotlin too. However it's marked as Deprecated and will be removed from common std lib soon.

I can see withLock, but it's supported on JVM only, not multiplatform.

Any thoughts?

PS. For now we don't want to migrate to Kotlin coroutines because of too much rewrite and coroutines library footprint (too large for Android library with strict disk footprint requirements).

3 Answers 3

5

From Kotlin/Native Concurrent documentation (here):

Concurrency in Kotlin/Native

Kotlin/Native runtime doesn't encourage a classical thread-oriented concurrency model with mutually exclusive code blocks and conditional variables, as this model is known to be error-prone and unreliable. Instead, we suggest a collection of alternative approaches, allowing you to use hardware concurrency and implement blocking IO. Those approaches are as follows, and they will be elaborated on in further sections:

  • Workers with message passing
  • Object subgraph ownership transfer
  • Object subgraph freezing
  • Object subgraph detachment
  • Raw shared memory using C globals
  • Coroutines for blocking operations (not covered in this document)

It seems that locks are not exposed in Kotlin/Native by design. There are implementations (see Lock.kt), however that class is marked internal.

However, there is a multi-platform implemenation of locks in KTOR (very limited doc, source code). It is public, but marked with @InternalApi, which may affect its stability.

You might also be interested in this KotlinLang discussion thread: Replacement for synchronized

4

There is no lock nor synchronized in Kotlin common. Kotlin's approach is to use immutable data. You can add your own expect AtomicReference in common and actual implementations in JVM Native, it will help a lot. Also keep in mind that coroutines in Native are single threaded at the moment. Also you can't share mutable state between threads in Native.

1
  • thanks for the "immutability" suggestion, I had an issue with concurrent modifications of a hash map, so returning a new HashMap solved the problem...
    – abdu
    Sep 5, 2022 at 13:34
3

There is full "lock" multi-platform implementation in Kotlin coroutines library. It is based on atomicfu and I think that can be easily extracted from there, even if you really don't want to depend from the full coroutine library:

1
  • > "can be easily extracted from there". How can it be done without copy/paste?
    – 4ntoine
    Dec 26, 2019 at 11:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.