Skip to content

Instantly share code, notes, and snippets.

@Gopinathp
Last active December 19, 2021 15:20
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 Gopinathp/fba8d764fc81e8465bf19528d371dadb to your computer and use it in GitHub Desktop.
Save Gopinathp/fba8d764fc81e8465bf19528d371dadb to your computer and use it in GitHub Desktop.
Idiomatic kotlin delegate method of using weak reference and soft reference in Java.
package delegates
import java.lang.ref.SoftReference
import java.lang.ref.WeakReference
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
fun <T>weakReference(tIn: T? = null): ReadWriteProperty<Any?, T?> {
return object : ReadWriteProperty<Any?, T?> {
var t = WeakReference<T?>(tIn)
override fun getValue(thisRef: Any?, property: KProperty<*>): T? {
return t.get()
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
t = WeakReference(value)
}
}
}
fun <T>softReference(tIn: T? = null): ReadWriteProperty<Any?, T?> {
return object : ReadWriteProperty<Any?, T?> {
var t = SoftReference<T?>(tIn)
override fun getValue(thisRef: Any?, property: KProperty<*>): T? {
return t.get()
}
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) {
t = SoftReference(value)
}
}
}
class Employee(val name: String, val id: String)
fun main() {
// This example may not work a expected, mostly because System.gc() need not trigger garbage collection.
// It is just a directive to the JVM but it need not trigger GC.
// There is no other way to simulate gc call other than triggering gc in a loop
run {
var employeeWeak: Employee? by weakReference(null)
employeeWeak = Employee("alok", "sjdfsdkjfdl")
println(employeeWeak?.name)
System.gc() // This may not trigger but it happens in JVM long running processes as needed.
println(employeeWeak?.name) // May be null if gc has been performed by the JVM.
}
run {
// Remember, soft reference are cleared only when there is a clear memory shortage
var employeeWeak: Employee? by softReference(Employee("gecko", "sjdfsdkjfd11l"))
println(employeeWeak?.name)
System.gc() // This may not trigger but it happens in JVM long running processes as needed.
println(employeeWeak?.name) // Need not be null. Mostly non-null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment