Skip to content

Instantly share code, notes, and snippets.

@Gopinathp
Last active July 14, 2022 22:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gopinathp/ad6a2c7f51d9e4d273c023203589648a to your computer and use it in GitHub Desktop.
Save Gopinathp/ad6a2c7f51d9e4d273c023203589648a to your computer and use it in GitHub Desktop.
Atomics.kt implementation
import java.util.concurrent.atomic.AtomicReference
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
private fun <T>atomicNullable(tIn: T? = null): ReadWriteProperty<Any?, T?> {
return object : ReadWriteProperty<Any?, T?> {
val t = AtomicReference<T>(tIn)
override fun getValue(thisRef: Any?, property: KProperty<*>): T? {
return t.get()
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
t.set(value)
}
}
}
private fun <T>atomic(tIn: T): ReadWriteProperty<Any?, T> {
return object : ReadWriteProperty<Any?, T> {
val t = AtomicReference<T>(tIn)
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return t.get()
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
t.set(value)
}
}
}
fun main() {
var aIntResource: Int? by atomicNullable(0)
var aLongResource: Long by atomic(0)
aIntResource = 1
aLongResource = 4L
println("Int Resource = $aIntResource")
println("Long Resource = $aLongResource")
aIntResource = 4
aLongResource = 100L
println("Modified Int Resource = $aIntResource")
println("Modified Long Resource = $aLongResource")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment