Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
demo of JNI local reference leak with JNI libraries, on HotSpot VM.
$ java -version
java version "1.6.0_25"
Java(TM) SE Runtime Environment (build 1.6.0_25-b06)
Java HotSpot(TM) 64-Bit Server VM (build 20.0-b11, mixed mode)
$ javac JNILocalRefLeakDemo.java
$ javah JNILocalRefLeakDemo
$ gcc -fPIC -shared -I $JAVA_HOME/include -I $JAVA_HOME/include/linux -o libleaky.so leaky.c
$ vi JNILocalRefLeakDemo.java
$ java -cp . -Djava.library.path=. JNILocalRefLeakDemo
Killed
$ sudo cat /var/log/messages | grep -i "killed process"
Aug 30 15:51:54 testmachine kernel: : Out of memory: Killed process 15605 (java).
Aug 30 16:10:48 testmachine kernel: : Out of memory: Killed process 15701 (java).
Aug 30 18:14:43 testmachine kernel: : Out of memory: Killed process 16255 (java).
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class JNILocalRefLeakDemo */
#ifndef _Included_JNILocalRefLeakDemo
#define _Included_JNILocalRefLeakDemo
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: JNILocalRefLeakDemo
* Method: foo
* Signature: (Ljava/lang/Object;)V
*/
JNIEXPORT void JNICALL Java_JNILocalRefLeakDemo_foo
(JNIEnv *, jclass, jobject);
#ifdef __cplusplus
}
#endif
#endif
public class JNILocalRefLeakDemo {
static {
System.loadLibrary("leaky");
}
public native static void foo(Object obj);
public static void main(String[] args) {
Object obj = new Object();
foo(obj);
}
}
#include "JNILocalRefLeakDemo.h"
void JNICALL Java_JNILocalRefLeakDemo_foo
(JNIEnv* env, jclass cls, jobject obj) {
for ( ; ; ) {
(*env)->NewLocalRef(env, obj);
}
}

I was looking for an example of JVM crash caused by running out of native memory (os::malloc() returning NULL) due to JNI local reference leak, but with this demo what I got was: the JVM got killed by the OOM killer after running it for a while. No crash logs, no core dumps, nothing; the Java process just went nowhere.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment