Skip to content

Instantly share code, notes, and snippets.

@ryohji
Last active June 5, 2019 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryohji/00308a1fbe78d90d00056895873140b3 to your computer and use it in GitHub Desktop.
Save ryohji/00308a1fbe78d90d00056895873140b3 to your computer and use it in GitHub Desktop.
The idea of single threaded execution in Kotlin Coroutine.
private val semaphore = AtomicBoolean(false)
private suspend fun Service.checkAndRefreshAccessToken() {
val aSecond = 1000L
  var mills = 1L
  // wait (binary-) semaphore to ensure only one coroutine
// executing this function's try ... catch body.
  while (!semaphore.compareAndSet(false, true)) {
    delay(millis)
    mills = minOf(aSecond, millis * 2)
  }
  try {
    // update token, if it will be expired soon.
    if (token.expiresIn(10 * aSecond)) {
      token.refresh() // NOTE: This is suspend function
    }
  } finally {
    // signal semaphore.
    semaphore.lazySet(false)
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment