Janik Zikovsky
Janik Zikovsky

Reputation: 3256

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 )?

Upvotes: 0

Views: 490

Answers (3)

Chris Dodd
Chris Dodd

Reputation: 126378

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.

Upvotes: 1

qwm
qwm

Reputation: 1035

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.

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272337

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.

Upvotes: 3

Related Questions