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

Time:10-17

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.

CodePudding user response:

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.

If a function or property is accessed solely from coroutines, then it does not need traditional synchronization.

  • Related