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.

Solution
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
    env->DeleteLocalRef(jstrString);
}


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

Additional Reference:
http://www.dynamicobjects.com/d2r/archives/001816.html


2 comments:

  1. Thanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog. It is very nicely explained. Your article adds best knowledge to our Java Online Training from India. or learn thru Java Online Training from India Students.

    ReplyDelete