hi, is there an alternative of @synchronized in km...
# multiplatform
n
hi, is there an alternative of @synchronized in kmm?
“Mutual exclusion solution to the problem is to protect all modifications of the shared state with a critical section that is never executed concurrently. In a blocking world you’d typically use
synchronized
or
ReentrantLock
for that. Coroutine’s alternative is called Mutex. It has lock and unlock functions to delimit a critical section. The key difference is that
Mutex.lock()
is a suspending function. It does not block a thread.”
k
There’s no language-level equivalent. Locks are the way to go. Atomic-fu (https://github.com/Kotlin/kotlinx.atomicfu) or Stately (https://github.com/touchlab/Stately, disclaimer, it’s ours) are libraries you could use for locks.
Doing an interesting thing in Koin now for the new memory model. Define an expect function
fun <R> synchronized(lock: Lockable, block: () -> R): R
.
Lockable
is an expect class
expect open class Lockable()
. See source: https://github.com/InsertKoinIO/koin/blob/3.2.x/core/koin-core/src/commonMain/kotlin/org/koin/mp/KoinPlatformTools.kt
On the JVM,
Lockable
is typealiased to
Any
, because any class in the JVM can be use for synchronize.
actual typealias Lockable = Any
. Source: https://github.com/InsertKoinIO/koin/blob/3.2.x/core/koin-core/src/jvmMain/kotlin/org/koin/mp/PlatformToolsJVM.kt
On native,
Lockable
is a class you need to extend, but it has a lock internally which you can use like
synchronize
on the JVM.
Copy code
actual open class Lockable {
    internal val lock = Lock()
}
Anyway, blog post overdue. This is all for the new memory model, btw. Old model is a whole different discussion.
👍 4
t
for the old memory model I can endorse stately (as a non-author)
👍 1
740 Views