Search code examples
kotlinkotlin-coroutineskotlin-android-extensions

Does @Synchronized or synchronized Keyword(s) Work on Kotlin Coroutines?


From some other StackOverflow answers, seems mutex is needed if you need to guard a property or function from concurrent coroutine execution. However, I happened to look at the source code of StateFlow.kt today and noticed:

This property is thread-safe and can be safely updated from concurrent coroutines without external synchronization.

Looking further into the implementation, all it has are a few traditional synchronized blocks without mutexes.

So the question is, does @Synchronized or synchronized keyword(s) work on Kotlin coroutines? The forum discussions mostly indicate they do not, but the official StateFlow implementation suggests otherwise.


Solution

  • They work, but Mutex's should be preferred because they can suspend, which avoids blocking a thread the way synchronized would.

    To make something truly thread-safe, such as StateFlow's value property, which can be set from any thread inside or outside of a coroutine, traditional synchronization is required.