Last active
June 5, 2019 09:17
-
-
Save ryohji/00308a1fbe78d90d00056895873140b3 to your computer and use it in GitHub Desktop.
The idea of single threaded execution in Kotlin Coroutine.
This file contains 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
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