gpt4 book ai didi

java - Java中调用native代码如何判断是不是内存泄漏?

转载 作者:可可西里 更新时间:2023-11-01 16:48:18 26 4
gpt4 key购买 nike

我在我的 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)。想知道这是内存泄漏还是我应该忽略它?或者这是否意味着 native 函数中存在内存泄漏?

仅供引用,我已经仔细检查了任何内存泄漏的 native 函数!

谢谢!

编辑:

原生函数:

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;
}

最佳答案

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

关于java - Java中调用native代码如何判断是不是内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8238328/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com