Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Java to call my C++ destructor (JNI)

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.

like image 333
Marc Bernier Avatar asked Jun 18 '09 19:06

Marc Bernier


People also ask

How do you trigger a destructor?

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() .

What is Jclass in JNI?

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 {}; ...


2 Answers

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();
}
like image 83
Gábor Hargitai Avatar answered Oct 04 '22 15:10

Gábor Hargitai


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.

like image 34
David Thornley Avatar answered Oct 04 '22 16:10

David Thornley