Created
March 26, 2020 18:41
-
-
Save kabutz/b44665953f00b3ea0ff6c2c09f2a0c66 to your computer and use it in GitHub Desktop.
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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Playing around with references of local variables, thread safe and not.