Skip to content

Instantly share code, notes, and snippets.

@JacquesSmuts
Last active June 2, 2019 07:38
Show Gist options
  • Save JacquesSmuts/bc1df2be0271ceffbda863cb43c66a68 to your computer and use it in GitHub Desktop.
Save JacquesSmuts/bc1df2be0271ceffbda863cb43c66a68 to your computer and use it in GitHub Desktop.
val lock = Any()
var latestValue: Int = 0
suspend fun runSuspendFunctionBadly(input: Int) {
println("running suspend function with input $input")
synchronized(lock) {
delay(1000)
latestValue = input
}
println("finished suspend function $input at ${System.currentTimeMillis()}")
}
companion object {
val mutex = Mutex()
}
var latestValue: Int = 0
suspend fun runSuspendFunctionWithMutex(input: Int) {
println("running suspend function with input $input")
mutex.withLock {
doubleOnServer(input)
println("finished suspend function $input at ${System.currentTimeMillis()}")
latestValue = input
}
}
val lock = Any()
var latestValue: Int = 0
fun runFunction(input: Int) {
println("running function with input $input")
synchronized(lock) {
Thread.sleep(1000)
latestValue = input
}
println("finished function $input at ${System.currentTimeMillis()}")
}
companion object {
val staticLock = Any()
}
var latestValue: Int = 0
fun runFunctionAcrossInstances(input: Int) {
println("running function with input $input")
synchronized(staticLock) {
Thread.sleep(1000)
latestValue = input
}
println("finished function $input at ${System.currentTimeMillis()}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment