Today I'm implementing a Closeable
in kotlin, and as I have done in java in the past, I want to implement a finalize()
as a last resort fallback in case the client code forgets to close it, rendering critical resource un-reclaimed. I consider this resource critical enough to add this fallback, despite the unreliability of this fallback. However, kotlin.Any
does not declare a finalize
method, which means I can't simplydo this:
class Resource: Closeable {
fun close() {}
override fun finalize() { close()}
}
This isn't good, at least not as good as it should be. Now I revert to plain Java as a workaround. Does anyone knows how to do this in pure Kotlin?
PS: My current workaround:
FinalizedCloseable.java:
public abstract class FinalizedCloseable implement Closeable {
@Override protected void finalize() { close(); }
}
Kotlin:
class Resource: FinalizedCloseable(), Closeable {
fun close() {}
override fun finalize() { close()}
}
But this workaround requires a superclass. If next time my other Resource
already got a superclass, this workaround won't work without a lot of boilerplate.
EDIT: Now I know how to implement finalize(), but IDEA kotlin plugin isn't smart enough to know that this is a finalizer and thus mark it with some warning. After struggling for a while I found how to suppress these warnings, and I want to share it:
class C {
@Suppress("ProtectedInFinal", "Unused") protected fun finalize() {}
}
native
code dealing with a system resource directly, your class will be a wrapper around another object actually representing the resource and letting the reachability of the wrapper determine the life time of the actual resource (which might still be reachable and in use), means asking for serious problems…FinalizeThis::finalize
in the example in your link is never called even once on my machine.