How can I use the same lock in both suspending and blocking code?
`Mutex`seems to be only usable in suspend functions and `synchronized()`only in non-suspend.
n
Nick Allen
12/10/2021, 6:03 PM
Coroutines themselves are multi-threaded and have to do synchronization. They tend to spin wait for synchronization using
atomic.loop
from
kotlinx.atomicfu
.
If the
synchronized
block is used for very fine grained synchronization such that blocking is insignificant if it even does happen, then I see no issue with using that from a coroutine. Don't suspend inside the block.
You can use
runBlocking
to run coroutines (like
Mutex
) from a non-suspending context. Only use this from places where blocking is expected and do not call if the code is running on a dispatcher so don't use