简体   繁体   中英

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

I have used JNI to call C methods that allocate memory. 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?

What happens to the "leaked" memory if you unload the loaded library (see How to unload library (DLL) from java JVM )?

When the JVM is stopped (is killed or exits) the OS will reclaim all the associated memory with that process. That includes any memory allocated within your native code.

Will happen all the same things that happens with ordinary C code. This memory will be leaked unless smth will reclaim it. For most modern OS it means resources will be freed when process exits. Unloading the JVM means nothing.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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