Skip to content

Instantly share code, notes, and snippets.

@rednaxelafx
Created September 1, 2011 11:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rednaxelafx/1185995 to your computer and use it in GitHub Desktop.
Save rednaxelafx/1185995 to your computer and use it in GitHub Desktop.
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