强制GC收集JNI代理对象 [英] Forcing the GC to collect JNI proxy objects
问题描述
有没有办法强制GC优先收集这些JNI代理?
我的意思是说有一种方法可以使GC集中精力一种特殊的对象,即JNI代理?
感谢。
如果您正在讨论在本机代码中分配的内存(以及扩展名为句柄),那么它不在JVM的垃圾收集器的权限范围之内 - 没有办法做到这一点,所以您是独立的。如果您在完成时未在本机代码中释放内存,它将会泄漏。
如果您引用的是通过其访问本机的Java对象代码,它们是完全正常的对象,当它们变得无法到达时将被收集。请注意,如果将Java对象固定在本机代码中(例如使用 GetByteArrayElements
),则还必须释放它们(例如,使用 ReleaseByteArrayElements
) 。如果您的本机代码在让Java对象离开之前必须释放资源,则Java对象应该具有某种类型的dispose方法,该方法在被调用时将释放本机资源并使Java对象无效,以免进一步使用。只需调用dispose方法并让对象引用即可。
最后一件事是,我意识到无法卸载本机库一旦加载。
While I do my best to clean JNI objects to free native memory in the end of the usage, there are still some that hang around for a long time, wasting system native memory.
Is there any way to force the GC to give priority in collection of these JNI proxies?
I mean is there a way to cause GC to concentrate on a particular kind of object, namely the JNI proxies?
Thanks.
If you are talking about memory (and, by extension, handles) allocated within native code, it is outside of the purview of the JVM's garbage collector - there is nothing it can do about it so you are on your own. If you don't release the memory in the native code when you are done, it will leak.
If you are referring to the Java objects through which you access the native code, they are perfectly normal objects which will be collected when they become unreachable. Note that if you pin Java objects in native code (e.g. with GetByteArrayElements
you must also release them (e.g. with ReleaseByteArrayElements
).
If your native code must release resources before you let the Java object go, the Java object should have a dispose method of some sort which when called will release the native resources and invalidate the Java object from further use. Simply call the dispose method and let the object reference go.
Once last thing, I am aware of no way to unload a native library once loaded.
这篇关于强制GC收集JNI代理对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!