[英]Memory leak in C++ program JNI environment
我有一個c ++程序,該程序依次調用JAVA函數(該函數調用一些API以獲取結果)。 Java調用的API會為服務器請求創建大量內存(每1000000個請求1 GB內存)。
我們可以從c / c ++程序中釋放內存嗎? 還是指示JVM釋放內存? 如果您可以提供幫助,那將是很大的幫助。
提前致謝...
謝謝Sambasiva。
制定明確的方法以釋放C ++程序中的所有資源
並嘗試在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();
}
}
除非可以修改第三方java類,否則您將無能為力。
如果您多次調用第三方java類,也會有很多風險
如果您強制從c ++中釋放資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.