Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++)?

like image 383
seahorse Avatar asked Jan 19 '12 13:01

seahorse


People also ask

Who performs garbage collection in Java?

Java garbage collection is an automatic process. The programmer does not need to explicitly mark objects to be deleted. The garbage collection implementation lives in the JVM. Each JVM can implement garbage collection however it pleases; the only requirement is that it meets the JVM specification.

Who is responsible for the Garbadge collection in Java?

Q #3) Who is responsible for Garbage Collection in Java? Answer: Memory management of Java has the responsibility of Garbage Collection.

Why do we need garbage collection in Java?

Java applications obtain objects in memory as needed. It is the task of garbage collection (GC) in the Java virtual machine (JVM) to automatically determine what memory is no longer being used by a Java application and to recycle this memory for other uses.


1 Answers

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.

like image 175
Peter Lawrey Avatar answered Sep 21 '22 14:09

Peter Lawrey