在c++中new的對象,若是不返回java,必須用release掉,不然內存泄露。包括NewStringUTF,NewObject。若是返回java沒必要release,java會本身回收。java
jstring jstr = env->NewStringUTF((*p).sess_id);
c++
...
windows
env->DeleteLocalRef( jstr);
jvm
jobject jobj = env->NewObject(clazz,midInit);
code
return jobj;
對象
內存泄露能夠先從windows資源管理器中,看到隨程序運行,內存不斷增加的趨勢,具體能夠用hp jmeter檢測。在運行程序時,加jvm參數 -Xrunhprof:heap=all,cutoff=0 ,生成java.hprof.txt,用jmeter打開,Metric -> Residual Objects (Count),能夠看到未回收的對象,選中要查看的對象,點Mark記錄下要查看的對象,Window -> New Window 打開新窗口,用Metric -> Reference Graph Tree,而後點Find Immediately能夠看到對象被哪裏引用。
整體原則:釋放全部對object的引用
1.FindClass 內存
jclass ref= (env)->FindClass("java/lang/String");
資源
env->DeleteLocalRef(ref);
input
2.NewString / NewStringUTF / NewObject / NewByteArray
例如,string
jstring (*NewString)(JNIEnv*, const jchar*, jsize);
const jchar* (*GetStringChars)(JNIEnv*, jstring, jboolean*);
void (*ReleaseStringChars)(JNIEnv*, jstring, const jchar*);
jstring (*NewStringUTF)(JNIEnv*, const char*);
const char* (*GetStringUTFChars)(JNIEnv*, jstring, jboolean*);
void (*ReleaseStringUTFChars)(JNIEnv*, jstring, const char*);
env->DeleteLocalRef(ref);
3.GetObjectField/GetObjectClass/GetObjectArrayElement
jclass ref = env->GetObjectClass(robj);
env->DeleteLocalRef(ref);
4.GetByteArrayElements和GetStringUTFChars
jbyte* array= (*env)->GetByteArrayElements(env,jarray,&isCopy);
(*env)->ReleaseByteArrayElements(env,jarray,array,0);
const char* input =(*env)->GetStringUTFChars(env,jinput, &isCopy);
(*env)->ReleaseStringUTFChars(env,jinput,input);
5.NewGlobalRef/DeleteGlobalRef
jobject (*NewGlobalRef)(JNIEnv*, jobject);
void (*DeleteGlobalRef)(JNIEnv*, jobject);
例如,
jobject ref= env->NewGlobalRef(customObj);
env->DeleteGlobalRef(customObj);