Skip to content

Instantly share code, notes, and snippets.

@CostaFot
Created January 8, 2020 23:56
Show Gist options
  • Save CostaFot/b1874b406f5fada7a5807ea26f033c3f to your computer and use it in GitHub Desktop.
Save CostaFot/b1874b406f5fada7a5807ea26f033c3f to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.newFixedThreadPoolContext
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.util.UUID
import java.util.concurrent.ConcurrentHashMap
fun main() = runBlocking {
val testyMcTest = TestyMcTest()
val scope = CoroutineScope(newFixedThreadPoolContext(4, "synchronizationPool"))
scope.launch {
val jobs: List<Job> = 1.rangeTo(NUMBER_OF_COROUTINES).map {
launch {
testyMcTest.addOnePairToMap()
testyMcTest.loopThroughMap()
}
}
jobs.forEach {
it.join() // wait for all coroutines to finish
}
}.join()
println("I should be equal to $NUMBER_OF_COROUTINES. Am I?")
println("Map size is ${testyMcTest.map.size}")
}
class TestyMcTest {
private val _mutableMap = mutableMapOf<UUID, UUID>()
val map: MutableMap<UUID, UUID>
get() = _mutableMap
suspend fun addOnePairToMap() {
withContext(Dispatchers.IO){
val randomUUID = UUID.randomUUID()
_mutableMap[randomUUID] = randomUUID
}
}
suspend fun loopThroughMap() {
withContext(Dispatchers.Default){
map.forEach {
// whatever
it.key.toString()
}
}
}
}
val NUMBER_OF_COROUTINES = 1000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment