内存库 java,释放Java中本机库分配的内存

If you are running code that makes calls to a native library in Java, what is the usual way of freeing memory allocated by these libraries when the memory allocation should last for the lifetime of the object? In C++, I would use destructors, but Java never really had those and has them even less now.

The specific case I'm most interested in is JOCL, where I have an object that wraps a compiled OpenCL kernel and all of the arguments thereto that are always the same. Structures representing the compiled kernel and the arguments are all allocated on the library side, and JOCL provides a method clReleaseMemObject that you call to decrement a reference counter indicating when the object should be deleted (note that this is a bit different from directly freeing the memory, but I don't think substantially so in this case).

I presume that if the object is still around when the program terminates, everything is cleaned up by the OS, but I'm not so sure about about objects created in a thread. So:

If you want the native memory deallocated when the object is garbage collected, is there a proper place to call the method that releases this memory?

If the object is one that will last for the duration of a thread, is there a proper place to make this call, or is this even necessary?

解决方案

What you can do is use a Cleaner. This is a more official API in Java 9 but is available in Java 1.4+.

Essentially you give it a Runnable to execute when the resource is cleaned up.

One advantage of using a Cleaner is you can call it to clean up deterministically, but if you forget or fail to do so, the GC will call it after it runs.

There isn't a safe way to clean up an object when a thread dies as the Thread object can live for the life of the program even if dead. A simpler approach is to clean up as you know it is not needed or after the GC determines it is not required.

Another approach is to use a reference queue and a background thread. It's not as elegant but works across Java 8 and later versions.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值