Skip to content

Instantly share code, notes, and snippets.

@kabutz
Created March 26, 2020 18:41
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 kabutz/b44665953f00b3ea0ff6c2c09f2a0c66 to your computer and use it in GitHub Desktop.
Save kabutz/b44665953f00b3ea0ff6c2c09f2a0c66 to your computer and use it in GitHub Desktop.
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.concurrent.thread
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
fun atomicBoolean(default: Boolean = false) =
object : ReadWriteProperty<Any?, Boolean> {
val storage = AtomicBoolean(default)
override fun getValue(thisRef: Any?, property: KProperty<*>) =
storage.get()
override fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean) =
storage.set(value)
}
fun main() {
fun threadSafeButUgly() {
println("threadSafeButUgly()")
val run = AtomicBoolean(false)
val thread = thread(start = true, block = { Thread.sleep(100); run.set(true) })
while (!run.get());
thread.join()
check(run.get()) { "run was set to $run" }
println("done")
}
fun threadSafeAndElegant() {
println("threadSafeAndElegant()")
var run by atomicBoolean()
val thread = thread(start = true, block = { Thread.sleep(100); run = true })
while (!run);
thread.join()
check(run) { "run was set to $run" }
println("done")
}
fun notThreadSafeButElegant() {
println("notThreadSafeButElegant()")
var run = false // implemented by Ref.BooleanRef
val thread = thread(start = true, block = { Thread.sleep(100);run = true })
while (!run);
thread.join()
check(run) { "run was set to $run" }
println("done")
}
threadSafeButUgly()
threadSafeAndElegant()
notThreadSafeButElegant() // does not return
}
@kabutz
Copy link
Author

kabutz commented Mar 26, 2020

Playing around with references of local variables, thread safe and not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment