I'm learning Coroutines in Kotlin and I have a piece of code that looks like this (see below).
My friend says that the mutableMapOf is LinkedHashMap, which is not thread safe. The argument is that the suspend function may be run by different threads, and thus LinkedHashMap is unsuitable.
- Is it safe to use a simple mutable map here or is ConcurrentMap needed?
- When a suspend function is suspended, can it be resumed and executed by another thread?
- Even if (2) is possible, is there "happens-before/ happens-after" guarantee that ensures all the variables (and the underlying object contents) are deep synchronized from main memory before the new thread takes over?
Here's a simplified version of the code:
class CoroutineTest {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
suspend fun simpleFunction(): MutableMap<Int,String> {
val myCallResults = mutableMapOf<Int,String>()
val deferredCallResult1 = scope.async {
//make rest call get string back
}
val deferredCallResult2 = scope.async {
//make rest call get string back
}
...
myCallResults.put( 1, deferredCallResult1.await() )
myCallResults.put( 2, deferredCallResult2.await() )
...
return myCallResults
}
}
Thanks in advance!
PS. I ran this code with much more async call results and had no problem; all call results are accounted for. But that can be inconclusive which is why I ask.