简体   繁体   English

C ++程序JNI环境中的内存泄漏

[英]Memory leak in C++ program JNI environment

I have c++ program which in turn calls JAVA function ( which calls some API to get the result). 我有一个c ++程序,该程序依次调用JAVA函数(该函数调用一些API以获取结果)。 The API which java is calling creating lot of memory to server request ( 1 GB memory for every 1000000 requests). Java调用的API会为服务器请求创建大量内存(每1000000个请求1 GB内存)。

Can we free the memory from c/c++ program? 我们可以从c / c ++程序中释放内存吗? or instruct the JVM to free the memory? 还是指示JVM释放内存? It would be great help if you can help on this. 如果您可以提供帮助,那将是很大的帮助。

Thanks in advance... 提前致谢...

Thanks Sambasiva. 谢谢Sambasiva。

Make explicit method that free all your resources in your C++ program 制定明确的方法以释放C ++程序中的所有资源

and try below code in your java class. 并尝试在Java类中使用以下代码。

/******************************************************************************/
/*  File        : NativeCodeHandle.java                                       */
/*  Description : Blog-posting or Educational purpose                         */
/*  Written     : 2010.07.11                                                  */
/*  Version     : -_+                                                         */
/*  Author      : a.k.a LaZy Developer                                        */
/*  Contacts    : chriskr7@gmail.com                                          */
/******************************************************************************/

class someNativeClass{
  public native void allocateSomeMemory();
  public native void freeSomeMemory();
  static
  {
    System.loadLibrary("someSoDLLFile");
  }
}

public class NativeCodeHandle {

  boolean isCleaned = false;

  someNativeClass nativeObject = new someNativeClass();

  public synchronized void allocate(){
    nativeObject.allocateSomeMemory();
  }

  public synchronized void cleanup(){
    if(isCleaned) return;
    // free native code - maybe JNI free() wrapper method    
    nativeObject.freeSomeMemory();
    // maybe close DB connection
  }

  public void finalize(){
    cleanup();
    try {
      super.finalize();
    } catch (Throwable e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }    
  }
 /**
   * @param args
   */
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    NativeCodeHandle test = new NativeCodeHandle();
    test.allocate();
    // Explicit clean up!!! :P
    test.cleanup();
  }

}

There is nothing you can do unless you can modify your third party java class . 除非可以修改第三方java类,否则您将无能为力。

Also there are many risk if you call the third party java class more than once 如果您多次调用第三方java类,也会有很多风险

if you force to free the resource from c++. 如果您强制从c ++中释放资源。

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

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