Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freeing memory wrapped with NewDirectByteBuffer

I have a region of memory wrapped with JNI NewDirectByteBuffer. I would like to run free/release code in the cleaner of the ByteBuffer. Is there a way to do this or do I have to offer a custom free method that the user will have to call with the ByteBuffer?

Edit

To clarify, I allocated the memory myself and called NewDirectByteBuffer myself. I would like to know how I should coordinate the clean up with the cleaner.

like image 661
Philippe Marschall Avatar asked Oct 20 '17 07:10

Philippe Marschall


1 Answers

You use JNI.newDirectByteBuffer, you can and you should free the memory manually, and do you clean up work at the same time.

If you want it clean up automatically, what you need is monitor the object's life cycle. And if you only want to work with API and don't use reflection, you can use a PhantomReference with ReferenceQueue, and create a demon thread to polling the queue. Do your clean up work once the reference be in the reference queue.

like image 50
Dean Xu Avatar answered Oct 18 '22 02:10

Dean Xu