My application makes multiple calls from native threads to java, i am seeing the memory usage of the application slowly creeping up. It looks like the calls to attach and detach cause JAVA to leak a thread. I can see this by running DDMS memory analyser.
I have written a really simple test app that demonstrates my issue, start test is called from JAVA and kicks off the thread. It doesn't do anything other then attach and then detach the worker thread.
void detachFromThread(JavaVM *vm)
{
if(vm != NULL)
{
vm->DetachCurrentThread();
}
else
{
__android_log_write(ANDROID_ LOG_ERROR, "JNI", "JNIUtils detachFromThread invalid VM passed in");
}
}
JNIEnv* attachToThread(bool &attached, JavaVM *vm)
{
JNIEnv *theJNIEnv(NULL);
attached = false;
if(vm != NULL)
{
jint result = vm->GetEnv((void **)& theJNIEnv, JNI_VERSION_1_6);
if (result != JNI_OK)
{
vm->AttachCurrentThread(&theJNIEnv, NULL);
if(theJNIEnv->ExceptionCheck())
{
theJNIEnv->ExceptionDescribe();
theJNIEnv->ExceptionClear();
__android_log_write(ANDROID_ LOG_ERROR, "JNI", "JNIUtils attachToThread failed to attach");
theJNIEnv = NULL;
}
else
{
attached = true;
}
}
}
else
{
__android_log_write(ANDROID_ LOG_ERROR, "JNI", "JNIUtils attachToThread invalid VM passed in");
}
return theJNIEnv;
}
bool checkForJNIException(JNIEnv * theJNIEnv)
{
bool ret = false;
if(theJNIEnv->ExceptionCheck())
{
ret = true;
__android_log_write(ANDROID_ LOG_ERROR, "JNI", "JNI Error occurred");
theJNIEnv->ExceptionDescribe();
theJNIEnv->ExceptionClear();
}
return ret;
}
void workerFunc(int noLoops)
{
for(int i = 0; i < noLoops; i++)
{
bool attached(false);
JNIEnv *testEnv = attachToThread(attached, g_vm);
if(attached)
detachFromThread(g_vm);
boost::posix_time::milliseconds sleepTime(1+ (rand()%(100)));
boost::this_thread::sleep(sleepTime);
}
}
void Java_com_example_testapp_ jnithreadtest_startTest(JNIEnv* env, jobject javaThis, int noLoops, int noThreads)
{
for(int i = 0; i < noThreads; i++)
boost::thread workerThread(workerFunc, noLoops);
}
Am i missing something, do I need to free something else up.