I thought this question would have been asked before, but I couldn't find it here...
I've used SWIG to create a JNI wrapper around a C++ class. All works great except that Java never seems to call the class's finalize(), so, in turn, my class's destructor never gets called. The class's destructor does some final file I/O, so unfortunately, this isn't just a minor memory leak.
Searching through Google, there doesn't seem to be a way to force Java to GC and destroy an object. True?
I know I could manipulate my SWIG file and create a java function that would call the C++ destructor, but this class is used by end users in several different platforms/languages, so the addition of a Java-only will create an inconsistency that our tech writers aren't going to like.
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete . A destructor has the same name as the class, preceded by a tilde ( ~ ). For example, the destructor for class String is declared: ~String() .
typedef jobject jclass; In C++, JNI introduces a set of dummy classes to enforce the subtyping relationship. For example: class _jobject {}; class _jclass : public _jobject {}; ...
You can't force GC with System.gc(). Also it is not guaranteed that there will ever be a GC run for example if your app runs only for a short time and then your finalizer won't run at all (the JVM does not run it when exiting). You should create a close() or destroy() or whatever function for your class and when you finished using an instance of this class call it, preferably from a finally block, like.
MyClass x = null;
try{
x = new MyClass();
x.work();
} finally {
if (x!=null)
x.close();
}
Java finalizers are mostly useless, in my opinion, and certainly not a replacement for C++ destructors. Unfortunately, Java has no replacement for C++ RAII.
Don't bother trying to force Java finalization. When you're through with the whatever, all a function that will dispose of it. That's all you can do.
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