Question

Ok, there is a C method called on a pointer which frees the memory area. I don't want my java binding user to explicitely call this method, because in java it makes no sense and this is a basically a data structure.

So, I just made a finalize() override putting there the c call. Anyway people say it is not good to rely on finalize...do you have any better idea?

Was it helpful?

Solution

There are a few problems with using the finalize method: you have no guarantee of when or if it will be called, it forces the garbage collector to do extra work, it's easy to get it wrong.

It is very common need to free resources, whether they are open file descriptors, window handles, database result sets, or something else. In these cases the classes have explicit close and dispose methods, which the user must call. I would suggest you follow the example set by these classes and add a close method. If you implement the AutoCloseable interface the API user will even be able to use the try-with-resources statement, and not have to call close() explicitly.

An alternative that's sometimes possible is creating a direct ByteBuffer and passing it to the C library, instead of the C library allocating memory on its own. The off-heap buffer is then freed when the ByteBuffer object is garbage collected. Incidentally, this is implemented using phantom references from the java.lang.ref package.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top