SHARE
TWEET

Untitled

a guest Jun 19th, 2019 65 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Thread safe check
  2. runBlocking {
  3.   val deferred = (1..20).map { n ->
  4.   GlobalScope.async {
  5.       val r = (1..10).random()
  6.       println("In ${n}")
  7.       try {
  8.         when {
  9.           r % 2 == 0 -> {
  10.             println("Create ${n} Thing1")
  11.             ThingFactory(Thing1::class)
  12.           }
  13.           else -> {
  14.             println("Create ${n} Thing2")
  15.             ThingFactory(Thing2::class)
  16.           }
  17.         }
  18.       } catch(e: RuntimeException) {
  19.         println("Error ${n} : ${e.message}")
  20.       }
  21.       println("Out ${n}")
  22.     }
  23.   }
  24.   deferred.awaitAll()
  25. //OUTPUT
  26. /*
  27. In 1
  28. Create 1 Thing1
  29. Out 1
  30. In 2
  31. Create 2 Thing2
  32. In 3
  33. Create 3 Thing1
  34. Out 3
  35. In 4
  36. Create 4 Thing1
  37. Out 4
  38. In 5
  39. Create 5 Thing1
  40. Out 5
  41. In 6
  42. Create 6 Thing1
  43. Out 6
  44. In 7
  45. Create 7 Thing2
  46. Error 2 : Already created as type:class Thing1
  47. Error 7 : Already created as type:class Thing1
  48. Out 7
  49. In 8
  50. Create 8 Thing2
  51. Error 8 : Already created as type:class Thing1
  52. Out 8
  53. In 9
  54. Create 9 Thing2
  55. Error 9 : Already created as type:class Thing1
  56. Out 9
  57. In 10
  58. Create 10 Thing2
  59. Error 10 : Already created as type:class Thing1
  60. Out 10
  61. In 11
  62. Create 11 Thing1
  63. Out 11
  64. In 12
  65. Create 12 Thing1
  66. Out 12
  67. In 13
  68. Create 13 Thing2
  69. Error 13 : Already created as type:class Thing1
  70. Out 13
  71. In 14
  72. Create 14 Thing1
  73. Out 2
  74. Out 14
  75. In 15
  76. Create 15 Thing1
  77. In 16
  78. Out 15
  79. Create 16 Thing2
  80. In 17
  81. Error 16 : Already created as type:class Thing1
  82. Create 17 Thing2
  83. Error 17 : Already created as type:class Thing1
  84. Out 17
  85. In 18
  86. Create 18 Thing2
  87. Error 18 : Already created as type:class Thing1
  88. Out 18
  89. In 19
  90. Create 19 Thing1
  91. Out 19
  92. In 20
  93. Create 20 Thing1
  94. Out 20
  95. Out 16
  96. */
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top