JNI: How to handle the creation/removal of wrapped C++ object
I'd like to wrap a C++ object so I can access it from Java. I have understood how to save a reference to my C++ object in my Java wrapper class by reading jni and using c++ new'ed objects in java. One thing I haven't figured out, though, is how to handle the creation and removal of my C++ object. Sure, I can introduce native methods that create and delete my C++ object but that means I have to take care of the memory management myself in Java...not very Javaish. Are there any native meth开发者_如何学Goods I should implement that gets called when my Java wrapper object is created and garbage collected?
You have to write native methods to create and destroy your c++ object. There are 3 different ways I know of how you could call those with java.
Implement the
public void finalize()
method for your java object. The garbage collector will call this method once your object is finalized so you can place the call to the destroy method here and the garbage collector will take care of everything. finalize() has its downsides, it slows the garbage collector down and will be called from a different thread to name a few.write a dispose() method and manage your memory by hand. This is used by swing/AWT for native resources. This gives you control over when and where the c++ object is deleted. You can still implement finalize() to stop memory leaks/debug your code.
Use the PhantomReference class and a ReferenceQueue to check if one of your Objects was garbage collected and delete the c++ object from there. This provides an alternative to finalize().
精彩评论