martmists
10/10/2023, 1:56 PMfinalize()
, but I can't find anything for native.
I'm aware native does provide Cleaner, but that requires the object to already be deallocated, meaning it's impossible to pass the object to some finalize method.
Ideally I could structure my code like this:
class C {
protected fun finalize() { ... }
private val cleaner = createCleaner(this) { this.finalize() }
}
but as the docs state, createCleaner(this) leaks a reference to C and it will never be deallocated.
What could I do here? Unfortunately putting a CleanerWrapper around every single class/instance is not feasible.Casey Brooks
10/10/2023, 2:03 PMfinalize()
is well-known to be a poor mechanism for cleaning up resources, and it’s better to use a more explicit mechanism in your own application logic. I’d recommend something like AutoCloseable (added in 1.8.20) and managing the lifecycle of those resources yourself with .use { }
ephemient
10/10/2023, 2:16 PMCleaner
concept for adding an action to after an object is collected,
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ref/Cleaner.html
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.native.ref/create-cleaner.html
but you need to be careful not to introduce reference cyclesfinalize()
is deprecated in most versions of Java and actually removed in the most recent: https://openjdk.org/jeps/421AutoCloseable
+ .use {}
in Kotlin, as Casey mentioned) or cleanersmartmists
10/10/2023, 3:15 PM