Tuesday, July 10, 2012

Fixing JNI Memory Leaks

During initial stages of my coding the application that I programmed use to re-start due to Java Exception "java.lang.OutOfMemoryerror". After much analysis, we found that making frequent JNI function calls caused the java.lang.OutOfMemoryError.

Reason for the problem - JNI Memory Leak
The reference for any object created in Java and sent to JNI native functions were not de-referenced automatically. Since these objects were not de-referenced, they couldn't be cleared by GC which caused the memory leak.

Please refer following sample code to free the memory.

JNIEXPORT jobject JNICALL Java_sample_package_SampleJavaClass_classMethod
(JNIEnv * env, jobject obj, jstring jstrString)
    const jchar* szString = (jchar*)env->GetStringChars(jstrString, 0);
    env->ReleaseStringChars(jstrString, (const jchar *)szString);
    // De-Referencing the String object

Considerable amount of Memory Leaks were fixed. Throughput is not 100%. 

Additional Reference:

No comments:

Post a Comment