Search code examples
javac++garbage-collectionjava-native-interface

JNI, Garbage collection and Pointers- Java/C++ who should do what?


We have the concept of pointers in C++. Now if we allocate some memory in C++ and pass it on to Java as an object reference(using JNI) then who should be and who will be freeing it.

Will it be

1.)The Garbage collector does it automatically in Java?

2.)We need to explicitly do a delete on the pointer in the wrapped JNI class finalize method?

3.)Or we should just forget finalize(as finalizers cannot be trusted) and it is responsibility of Java to call a C++ code which deletes the object

4.)Or is there some way to deallocate the memory directly in Java itself (not sure how Java intreprets a C++ pointer inorder to delete it)?

What is the best practice for doing this and vice versa(when we pass objects from Java to C++)?


Solution

  • We have the concept of pointers in C++. Now if we allocate some memory in C++ and pass it on to Java as an object reference(using JNI) then who should be and who will be freeing it.

    The best strategy is usually to have the allocator also be the one to free the data.

    1.)The Garbage collector does it automatically in Java?

    The problem with this is you don't know when, if ever it will run.

    2.)We need to explicitly do a delete on the pointer in the wrapped JNI class finalize method?

    Better to have a release() method in Java rather than imply that C++ has to delete it. You may want C++ to recycle the memory.

    3.)Or we should just forget finalize(as finalizers cannot be trusted) and it is responsibility of Java to call a C++ code which deletes the object

    If you mean, allocate the memory in Java and pass it to C++ to populate. This is my preference.

    I would use can use ByteBuffer.allocateDirect() and you can call ((DirectBuffer) buffer).cleaner().clean(); to clean it up deterministically.

    This can make recycling the memory simpler, possibly the same buffer can be used for the life of the application.