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() {} }
Java Object finalize() MethodFinalize() is the method of Object class. This method is called just before an object is garbage collected. finalize() method overrides to dispose system resources, perform clean-up activities and minimize memory leaks.
Overview. Finalize method in Java is an Object Class method that is used to perform cleanup activity before destroying any object. It is called by Garbage collector before destroying the object from memory. Finalize() method is called by default for every object before its deletion.
The finalize() method is a pre-defined method in the Object class and it is protected. The purpose of a finalize() method can be overridden for an object to include the cleanup code or to dispose of the system resources that can be done before the object is garbage collected.
System. gc() forces the garbage collector to run, while the Finalize() method of your object defines what garbage collector should do when collecting this specific object.
The official documentation covers this.
To override finalize(), all you need to do is simply declare it, without using the override keyword:
class C { protected fun finalize() { // finalization logic } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With