Last active
July 14, 2022 22:50
-
-
Save Gopinathp/ad6a2c7f51d9e4d273c023203589648a to your computer and use it in GitHub Desktop.
Atomics.kt implementation
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.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