当通过JNI从本机线程回调时,Java线程泄漏
小结:当从本机创建的线程上的本机代码调用Java时,我看到Java线程泄漏 (2014年2月11日更新:我们将此作为对Oracle的支持请求提出。Oracle现在已经在Java 7 Update 45上发布了此请求。它只影响64位Linux(可能还有Mac)平台:32位Linux不受影响) (2014年4月29日更新:Oracle对此问题进行了修复,并将在Java 7 Update 80中发布) 我有一个由Java层和本机库组成的应用程序。Java层通过JNI调用本机库:这会导致一个新的本机线程开始运行,从而调用回Java。因为新的本机线程没有连接到JVM,所以需要在执行回调之前连接它,然后再分离。通常的方法似乎是用AttachCurrentThread/DetachCurrentThread调用将调用回Java的代码括起来。这很好,但是对于我们的应用程序(它非常频繁地调用Java)来说,每次附加和分离的开销是非常大的 有几个地方(如和)描述了一个优化,建议使用基于线程本地存储的机制来消除这个问题:基本上每次触发本机回调时,都会测试线程是否已经连接到JVM:如果没有,它连接到JVM,线程本地存储机制用于在线程退出时自动分离线程。我已经实现了这一点,但是尽管附加和分离看起来是正确的,但这会导致Java端的线程泄漏。我相信我做的每一件事都是正确的,我正在努力寻找可能的错误。我已经在这个问题上苦思冥想了一段时间,如果有任何见解,我将不胜感激 我以简化的形式重新创建了这个问题。下面是本机层的代码。我们这里有一个包装器,它封装了为当前线程返回JNIEnv指针的过程,使用POSIX线程本地存储机制自动分离尚未连接的线程。有一个回调类充当Java回调方法的代理。(我使用了对静态Java方法的回调,以消除创建和删除Java对象的全局对象引用的额外复杂性,这与此问题无关)。最后还有一个JNI方法,它在被调用时构造一个回调,并创建一个新的本机线程并等待它完成。这个新创建的线程在退出后调用回调当通过JNI从本机线程回调时,Java线程泄漏,java,c++,multithreading,callback,java-native-interface,Java,C++,Multithreading,Callback,Java Native Interface,小结:当从本机创建的线程上的本机代码调用Java时,我看到Java线程泄漏 (2014年2月11日更新:我们将此作为对Oracle的支持请求提出。Oracle现在已经在Java 7 Update 45上发布了此请求。它只影响64位Linux(可能还有Mac)平台:32位Linux不受影响) (2014年4月29日更新:Oracle对此问题进行了修复,并将在Java 7 Update 80中发布) 我有一个由Java层和本机库组成的应用程序。Java层通过JNI调用本机库:这会导致一个新的本机线程
#include <jni.h>
#include <iostream>
#include <pthread.h>
using namespace std;
/// Class to automatically handle getting thread-specific JNIEnv instance,
/// and detaching it when no longer required
class JEnvWrapper
{
public:
static JEnvWrapper &getInstance()
{
static JEnvWrapper wrapper;
return wrapper;
}
JNIEnv* getEnv(JavaVM *jvm)
{
JNIEnv *env = 0;
jint result = jvm->GetEnv((void **) &env, JNI_VERSION_1_6);
if (result != JNI_OK)
{
result = jvm->AttachCurrentThread((void **) &env, NULL);
if (result != JNI_OK)
{
cout << "Failed to attach current thread " << pthread_self() << endl;
}
else
{
cout << "Successfully attached native thread " << pthread_self() << endl;
}
// ...and register for detach when thread exits
int result = pthread_setspecific(key, (void *) env);
if (result != 0)
{
cout << "Problem registering for detach" << endl;
}
else
{
cout << "Successfully registered for detach" << endl;
}
}
return env;
}
private:
JEnvWrapper()
{
// Initialize the key
pthread_once(&key_once, make_key);
}
static void make_key()
{
pthread_key_create(&key, detachThread);
}
static void detachThread(void *p)
{
if (p != 0)
{
JavaVM *jvm = 0;
JNIEnv *env = (JNIEnv *) p;
env->GetJavaVM(&jvm);
jint result = jvm->DetachCurrentThread();
if (result != JNI_OK)
{
cout << "Failed to detach current thread " << pthread_self() << endl;
}
else
{
cout << "Successfully detached native thread " << pthread_self() << endl;
}
}
}
static pthread_key_t key;
static pthread_once_t key_once;
};
pthread_key_t JEnvWrapper::key;
pthread_once_t JEnvWrapper::key_once = PTHREAD_ONCE_INIT;
class Callback
{
public:
Callback(JNIEnv *env, jobject callback_object)
{
cout << "Constructing callback" << endl;
const char *method_name = "javaCallback";
const char *method_sig = "(J)V";
env->GetJavaVM(&m_jvm);
m_callback_class = env->GetObjectClass(callback_object);
m_methodID = env->GetStaticMethodID(m_callback_class, method_name, method_sig);
if (m_methodID == 0)
{
cout << "Couldn't get method id" << endl;
}
}
~Callback()
{
cout << "Deleting callback" << endl;
}
void callback()
{
JNIEnv *env = JEnvWrapper::getInstance().getEnv(m_jvm);
env->CallStaticVoidMethod(m_callback_class, m_methodID, (jlong) pthread_self());
}
private:
jclass m_callback_class;
jmethodID m_methodID;
JavaVM *m_jvm;
};
void *do_callback(void *p)
{
Callback *callback = (Callback *) p;
callback->callback();
pthread_exit(NULL);
}
extern "C"
{
JNIEXPORT void JNICALL Java_com_test_callback_CallbackTest_CallbackMultiThread(JNIEnv *env, jobject obj)
{
Callback callback(env, obj);
pthread_t thread;
pthread_attr_t attr;
void *status;
int rc;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
rc = pthread_create(&thread, &attr, do_callback, (void *) &callback);
pthread_attr_destroy(&attr);
if (rc)
{
cout << "Error creating thread: " << rc << endl;
}
else
{
rc = pthread_join(thread, &status);
if (rc)
{
cout << "Error returning from join " << rc << endl;
}
}
}
只需补充:我使用的开发平台是CentOS 6.3(64位)。Java版本是Oracle发行版1.7.045,尽管OpenJDK发行版1.7和1.6版本也存在此问题。Oracle已通过JVM解决了此问题,并将在Java 7 update 80中发布 如果你不打算接受你自己的答案,也许你会接受这个。
至少对于一个零答案的问题,它不会再吸引那么多的流量了。有点奇怪,所有本机句柄都是相同的140503373506304。这个问题似乎局限于64位Linux(见RHEL和克隆)。Oracle现在已经确认了这个问题:更新了带有链接的说明。尚未修复…提出问题,确定为bug。我怎样才能给你更多的声誉@MalcolmWilkins您应该自己回答这个问题,确认它是JVM中的一个bug,并且是在哪个版本中修复的。
package com.test.callback;
public class CallbackTest
{
static
{
System.loadLibrary("Native");
}
public void runTest_MultiThreaded(int trials)
{
for (int trial = 0; trial < trials; trial++)
{
// Call back from this thread
CallbackMultiThread();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
static void javaCallback(long nativeThread)
{
System.out.println("Java callback: native thread: " + nativeThread + ", java thread: " + Thread.currentThread().getName() + ", " + Thread.activeCount() + " active threads");
}
native void CallbackMultiThread();
}
Constructing callback
Successfully attached native thread 140503373506304
Successfully registered for detach
Java callback: native thread: 140503373506304, java thread: Thread-67, 69 active threads
Successfully detached native thread 140503373506304
Deleting callback
Constructing callback
Successfully attached native thread 140503373506304
Successfully registered for detach
Java callback: native thread: 140503373506304, java thread: Thread-68, 70 active threads
Successfully detached native thread 140503373506304
Deleting callback
Constructing callback
Successfully attached native thread 140503373506304
Successfully registered for detach
Java callback: native thread: 140503373506304, java thread: Thread-69, 71 active threads
Successfully detached native thread 140503373506304
Deleting callback
Constructing callback
Successfully attached native thread 140503373506304
Successfully registered for detach
Java callback: native thread: 140503373506304, java thread: Thread-70, 72 active threads
Successfully detached native thread 140503373506304
Deleting callback
Constructing callback
Successfully attached native thread 140503373506304
Successfully registered for detach
Java callback: native thread: 140503373506304, java thread: Thread-71, 73 active threads
Successfully detached native thread 140503373506304
Deleting callback