jarinel

Sync long function call POC

Oct 11th, 2019
687
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.40 KB | None | 0 0
  1. import kotlinx.coroutines.*
  2. import kotlinx.coroutines.sync.Mutex
  3. import kotlinx.coroutines.sync.withLock
  4. import java.util.*
  5. import kotlin.coroutines.CoroutineContext
  6. import kotlin.random.Random
  7.  
  8. val random = Random(Date().time)
  9.  
  10. suspend fun slowRequest(): Long {
  11.     delay(3000)
  12.     return random.nextLong(0, 1000)
  13. }
  14.  
  15. class Manager(
  16.         private val context: CoroutineContext
  17. ) {
  18.     private var state: Deferred<Long>? = null
  19.     private val mutex = Mutex()
  20.     private val list: MutableList<Deferred<Long>> = mutableListOf()
  21.  
  22.     private suspend fun startSlowRequest() = coroutineScope {
  23.         if (state == null) {
  24.             state = async {
  25.                 val result = slowRequest()
  26.                 launch(context) { clear() }
  27.                 result
  28.             }
  29.         }
  30.     }
  31.  
  32.     private suspend fun clear() = coroutineScope {
  33.         mutex.withLock {
  34.             list.forEach { it.join() }
  35.             list.clear()
  36.             state = null
  37.         }
  38.     }
  39.  
  40.     suspend fun slow(): Long = coroutineScope {
  41.         mutex.withLock {
  42.             startSlowRequest()
  43.             val invocation = async { state!!.await() }
  44.             list.add(invocation)
  45.             invocation
  46.         }.await()
  47.     }
  48. }
  49.  
  50.  
  51. fun main() = runBlocking {
  52.     val manager = Manager(coroutineContext)
  53.  
  54.     repeat(23) {
  55.         launch { println(manager.slow()) }
  56.         delay(500)
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment