1. 程式人生 > >7.JNI 記憶體洩漏 處理 方法總結

7.JNI 記憶體洩漏 處理 方法總結

在c++中new的物件,如果不返回java,必須用release掉,否則記憶體洩露。包括NewStringUTF,NewObject。如果返回java不必release,java會自己回收。

jstring jstr = env->NewStringUTF((*p).sess_id);
   ...
env->DeleteLocalRef( jstr);
 
jobject jobj = env->NewObject(clazz,midInit);
return jobj;

總體原則:釋放所有對object的引用

1.FindClass

jclass ref= (env)->FindClass("java/lang/String");
 
env->DeleteLocalRef(ref); 

2.NewString / NewStringUTF / NewObject / NewByteArray

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

6.JVM:AttachCurrentThread/ DetachCurrentThread

#include <jni.h>
#include <stdio.h>
#include <malloc.h>
#include "logUtils.h"


static JavaVM  *jvm=NULL;
static jobject  jobj_callback=NULL;
static jmethodID  mid=NULL;
static int flag=-1;
static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond=PTHREAD_COND_INITIALIZER;


//在載入庫時執行;
 jint JNI_OnLoad(JavaVM *vm,void *reserved){
    jvm=vm;
    LOGE("------- JNI_OnLoad -------");
    return JNI_VERSION_1_6;
}
//在解除安裝庫時執行
 void JNI_OnUnload(JavaVM *vm,void *reserved){
    jvm=NULL;
    LOGE("------- JNI_OnUnload -------");
}
//pthread中執行的函式
static void *nativeWork(void*args){
    LOGE(" ==================== pre nativeWork ==================== ");
    JNIEnv *env=NULL;
    //附加到當前執行緒從JVM中取出JNIEnv, C/C++從子執行緒中直接回到Java裡的方法時  必須經過這個步驟
    if( (*jvm)->AttachCurrentThread(jvm,&env,NULL)==0 ){
        while (flag==0){
            if( jobj_callback==NULL ){
                //進入等待
                pthread_cond_wait(&cond,&mutex);
            } else{
                //回撥java中的執行緒
                (*env)->CallVoidMethod(env,jobj_callback,mid);
                (*env)->DeleteGlobalRef(env,jobj_callback);
                jobj_callback=NULL;
            }
        }
        //完畢-脫離當前執行緒
        (*jvm)->DetachCurrentThread(jvm);
    }
    LOGE(" ==================== end nativeWork ==================== ");
    return (void*)1;
}