Skip to content

Instantly share code, notes, and snippets.

@markmaynard
Created June 8, 2019 15:21
Show Gist options
  • Save markmaynard/9a6fd0f6dae635b5cb7863776d2aee9e to your computer and use it in GitHub Desktop.
Save markmaynard/9a6fd0f6dae635b5cb7863776d2aee9e to your computer and use it in GitHub Desktop.
Thread safe test
// Thread safe check
runBlocking {
val deferred = (1..20).map { n ->
GlobalScope.async {
val r = (1..10).random()
println("In ${n}")
try {
when {
r % 2 == 0 -> {
println("Create ${n} Thing1")
ThingFactory(Thing1::class)
}
else -> {
println("Create ${n} Thing2")
ThingFactory(Thing2::class)
}
}
} catch(e: RuntimeException) {
println("Error ${n} : ${e.message}")
}
println("Out ${n}")
}
}
deferred.awaitAll()
//OUTPUT
/*
In 1
Create 1 Thing1
Out 1
In 2
Create 2 Thing2
In 3
Create 3 Thing1
Out 3
In 4
Create 4 Thing1
Out 4
In 5
Create 5 Thing1
Out 5
In 6
Create 6 Thing1
Out 6
In 7
Create 7 Thing2
Error 2 : Already created as type:class Thing1
Error 7 : Already created as type:class Thing1
Out 7
In 8
Create 8 Thing2
Error 8 : Already created as type:class Thing1
Out 8
In 9
Create 9 Thing2
Error 9 : Already created as type:class Thing1
Out 9
In 10
Create 10 Thing2
Error 10 : Already created as type:class Thing1
Out 10
In 11
Create 11 Thing1
Out 11
In 12
Create 12 Thing1
Out 12
In 13
Create 13 Thing2
Error 13 : Already created as type:class Thing1
Out 13
In 14
Create 14 Thing1
Out 2
Out 14
In 15
Create 15 Thing1
In 16
Out 15
Create 16 Thing2
In 17
Error 16 : Already created as type:class Thing1
Create 17 Thing2
Error 17 : Already created as type:class Thing1
Out 17
In 18
Create 18 Thing2
Error 18 : Already created as type:class Thing1
Out 18
In 19
Create 19 Thing1
Out 19
In 20
Create 20 Thing1
Out 20
Out 16
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment