在Java中调用本机代码时如何知道是否存在内存泄漏?

时间:2011-11-23 06:56:04

标签: java c++ memory-leaks java-native-interface

我在main中调用一个本机函数,它在while循环中。

public static void main (String[] args) throws Throwable {

        testDLL test = new testDLL();
        String ar[];
        while (true){
            System.out.println("Memory before garbage collection: " + Runtime.getRuntime().freeMemory());           
            ar = test.GetSomething("###");      
            test.finalize();
            System.gc();
            Thread.sleep(5000);
            System.out.println("Memory after garbage collection: " + Runtime.getRuntime().freeMemory());
            System.out.println();
        }
}

以下程序的输出是:(运行约1分钟)

Memory before garbage collection: 1915288
Memory after garbage collection: 1915136

Memory before garbage collection: 1915136
Memory after garbage collection: 1914984

Memory before garbage collection: 1914984
Memory after garbage collection: 1916624

Memory before garbage collection: 1916624
Memory after garbage collection: 1916472

Memory before garbage collection: 1916472
Memory after garbage collection: 1916320

Memory before garbage collection: 1916320
Memory after garbage collection: 1916168

Memory before garbage collection: 1916168
Memory after garbage collection: 1916624

Memory before garbage collection: 1916624
Memory after garbage collection: 1916472

我猜这不是内存泄漏。但是,当我打开Windows的任务管理器时,进程javaw.exe的大小不断增加(迭代时每次100 KB)。想知道它是否是内存泄漏还是我应该忽略它?或者这是否意味着本机函数中存在内存泄漏?

仅供参考我已经仔细检查了我的本机功能是否有任何内存泄漏!

谢谢!

修改

原生功能:

JNIEXPORT jobjectArray JNICALL Java_testDLL_GetSomething
(JNIEnv * env, jobject jobj, jstring approvedJString){

    const int num = 100;

    jboolean * isCopy;
    jobjectArray serialNumArrJobj;
    const char* approved = env->GetStringUTFChars(approvedJString, isCopy);
    string serialNumArr[num];

    //*
    *   Long lengthy code here
    *   Populates the string array "serialNumArr"
    *//

    // ========

    env->ReleaseStringUTFChars(approvedJString, approved);
    env->DeleteLocalRef(approvedJString);
    env->DeleteLocalRef(jobj);

    ////////////

    int i, sizeOfArr = 0;

    for( i = 0; i < num; i++) {
        if (serialNumArr[i].empty())
            break;
        else
            sizeOfArr++;
    }

    serialNumArrJobj = (jobjectArray)env->NewObjectArray(sizeOfArr,
         env->FindClass("java/lang/String"),
         env->NewStringUTF(""));


    for( i = 0; i < sizeOfArr; i++) {
        env->SetObjectArrayElement(serialNumArrJobj,
            i,
            env->NewStringUTF(serialNumArr[i].c_str()));
    }

    return serialNumArrJobj;
}

2 个答案:

答案 0 :(得分:1)

你的期望是错误的。您不能指望System.gc()不仅仅是对垃圾收集器的提示,而且自己调用finalize()是完全错误的。

答案 1 :(得分:0)

我认为您需要编写直接调用本机代码的单元测试,如Java代码,如Mock测试。