Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Languaged bindings involving non-gced memory for languages without guaranteed destructors?

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?

like image 763
compman Avatar asked Oct 10 '22 10:10

compman


1 Answers

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.

like image 74
stolsvik Avatar answered Oct 20 '22 06:10

stolsvik