Last active
January 8, 2020 23:56
-
-
Save CostaFot/b4bb4d9e6c68d6d9087d9846f39b4549 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 _concurrentHashMap = ConcurrentHashMap<UUID, UUID>() | |
val map: ConcurrentHashMap<UUID, UUID> | |
get() = _concurrentHashMap | |
suspend fun addOnePairToMap() { | |
withContext(Dispatchers.IO){ | |
val randomUUID = UUID.randomUUID() | |
_concurrentHashMap[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