简体   繁体   English

如果从Java JNI分配的本机代码中泄漏内存,会发生什么情况?

[英]What happens if you leak memory in native code allocated from Java JNI?

I have used JNI to call C methods that allocate memory. 我已经使用JNI调用了分配内存的C方法。 I have methods to free the memory, but if those methods are not called, what happens to the allocated memory when the JVM is stopped? 我有释放内存的方法,但是如果不调用这些方法,那么在JVM停止时分配的内存会如何处理?

What happens to the "leaked" memory if you unload the loaded library (see How to unload library (DLL) from java JVM )? 如果您卸载已加载的库(请参阅如何从Java JVM卸载库(DLL)), “泄漏的”内存会发生什么?

When the JVM is stopped (is killed or exits) the OS will reclaim all the associated memory with that process. 当JVM停止(被杀死或退出)时,操作系统将回收与该进程相关的所有内存。 That includes any memory allocated within your native code. 这包括在您的本机代码中分配的所有内存。

Will happen all the same things that happens with ordinary C code. 将发生与普通C代码相同的所有事情。 This memory will be leaked unless smth will reclaim it. 除非smth将其回收,否则该内存将被泄漏。 For most modern OS it means resources will be freed when process exits. 对于大多数现代OS,这意味着在进程退出时将释放资源。 Unloading the JVM means nothing. 卸载JVM毫无意义。

The usual method of avoiding this problem is to have the C-allocated memory strongly associated with some java object, and have a finalizer on that java object which calls the JNI method to free the memory. 避免此问题的常用方法是使C分配的内存与某个Java对象紧密关联,并在该Java对象上具有终结器,该终结器调用JNI方法以释放内存。 That way things will get cleaned up by the garbage collector and the user of your library doesn't need to remember to cal the cleanup JNI method. 这样,垃圾收集器将清理所有内容,并且库的用户无需记住要校准清理JNI方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM