Hong Phuc
12/17/2024, 10:16 AMDispatcher
? Thanks in advanceJoffrey
12/17/2024, 11:25 AMJoffrey
12/17/2024, 11:26 AMDispatchers.Default
, <http://Dispatchers.IO|Dispatchers.IO>
, custom dispatchers created from JVM ExecutorService
, etc.Joffrey
12/17/2024, 11:30 AMDispatchers.Main
), or on multiple dispatchers backed by the same thread, then the problem doesn't occur and you don't need special synchronization between these coroutines. That said, multiple coroutines running on different dispatchers, even single-threaded, will need synchronization because they effectively run on different threads.uli
12/17/2024, 2:21 PMuli
12/17/2024, 2:23 PMHong Phuc
12/17/2024, 10:08 PMCLOVIS
12/18/2024, 9:55 AMHong Phuc
12/18/2024, 12:35 PMCLOVIS
12/18/2024, 1:06 PMuli
12/18/2024, 2:10 PMif the solution is that straight-forward why there are many not applying itBecause it requires the right architecture. I.e.if you have (come up) with a solution using mutable state, you cannot transform it into an immutable state solution with some local changes. There is one important quick win with coroutines compared to threads. Coroutines are sequential! That means, even when you switch threads with
withContext
, your whole coroutine behaves like single threaded. (It can still race with other coroutines though).
In below example, there is no risk with regards to x, even though x is mutable and x is shared between main thread and a thread from the io dispatcher.
Coroutines have “happens before” guarantees, just as regular code, even when switching threads.
var x: Int = 0
launch(Dispatchers.Main) {
x = x + 1
withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
x = x + fetchNumberFromServer()
}
x = x - 1
}
Hong Phuc
12/20/2024, 2:53 AMCLOVIS
12/20/2024, 8:49 AMemptyList()
is free because it always returns the exact same instance? It never creates a new list). If you have Effective Java, all the points mentioned there apply to Kotlin as well.Hong Phuc
12/21/2024, 1:25 AMCLOVIS
12/21/2024, 9:25 AM