且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 JNI 从 C 调用 java 代码时的内存泄漏

更新时间:2023-08-19 15:48:22

When you call New... functions, you create a "local reference" - reference to this object in local stack frame. This prevents Java VM from GC this object while you still need it. This is fine if you are implementing some native method - its local frame is created only for method call duration. But when you are creating object from a native java-attached thread, it becomes bound to this thread stack frame, which will be destroyed only with this thread.

So, when you done with an object you can call DeleteLocalRef() to tell you no longer need it. Or you can surround the whole add() function with pair of PushLocalFrame()/PopLocalFrame() to make a separate local frame for its duration.