When someone is making bindings from a C library to Java (or any other garbage-collected language without destructors that are guaranteed to run), how do they deal with proper deallocation of non-garbage-collected memory?
EDIT: What I'm thinking of (I know this isn't explicitly state in my original question) is when a piece of non-gc'ed memory holds references to other non-gc'ed resources that need to be freed when that object is freed. For example, if you have a non-gc'ed linked list node that is the head of a long list of such nodes and you want to have the gc system clean it up automatically eventually, how do you set that up?
In java, you have the finalize() concept. You can free the C-memory there.
However, probably a better way is to use PhantomReferences along with a ReferenceQueue. You can extend the PhantomReference class so that it holds some id or pointer or whatever to the C-side memory you need to free. When it is enqueued in the ReferenceQueue, you can then free the C-side memory that this id points to - the Java object is guaranteed to not be in existence "in Java" anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With