2

I want to wrap a C++ library using the Java Native Interface. I wonder how memory management can be done, because afaik Object.finalize() is not garuanteed to be called. I would like to avoid that the user needs to call a free() method. Also, the library would be used in an embeded system, that means some of the objects are owned by the application and some by the Java runtime. When the Java plugin saves a reference to memory that is owned by the application it may happen that the application has already freed it and therefore the reference is invalid.

Was that clear enough?

Thanks,

Niklas R
  • 14,369
  • 23
  • 82
  • 179
  • See http://stackoverflow.com/questions/2412964/forcing-the-gc-to-collect-jni-proxy-objects – Code Painters Nov 10 '12 at 15:17
  • 1
    @Niklas please explain why you would like to avoid the user needing to call explicit disposal method. AFAIK there is no other reliable solution. – Pavel Zdenek Nov 10 '12 at 17:36
  • @PavelZdenek Because it's one of the benefits of a language with garbage collection to not care for memory management. But if you say it is the only way.. :/ – Niklas R Nov 10 '12 at 17:53
  • @Niklas well by embracing JNI, you voluntarily lost carefree GC :) For more info and some recommended reading about finalizers, see http://stackoverflow.com/a/13046607/886653 – Pavel Zdenek Nov 10 '12 at 21:33
  • 1
    Java can't automagically detect when native code has deallocated some chunk of native memory it doesn't manage. You need to give Java full control if you want to take advantage of its garbage collection facilities safely. – Samuel Audet Nov 16 '12 at 02:28
  • @SamuelAudet By *full control*, you mean to expose the memory management (freeing, allocation is usually done with the constructor) to the Java interface? – Niklas R Nov 16 '12 at 12:23
  • Yes, have the memory available to Java as long as it can be used by Java. Obviously you could modify your native code to notify Java when it frees memory, but that requires modification to the existing library. – Samuel Audet Nov 17 '12 at 13:29
  • Depending on what you need to free, you must either give control to Java via JNI as Samuel already pointed out or call free() on JNI_OnUnload(). – Alex Barker Dec 03 '13 at 23:16

0 Answers0