JNI - multi threads

c++, java, java-native-interface, multithreading

Solution

Please refer to the documentation to the chapter `Attaching to the VM`.

You need to call `AttachCurrentThread()` for each native thread at least once before you can use any of the JNI functions. Thread created in Java are already attached. So I your example whenever the `GetEnv` call fails call `AttachCurrentThread()` and you should be fine. Or make sure that whenver you create a sub thread you attach it to the VM.

Problem

I have a JNI wrapper for Java functions that are called from C... I'm trying to call some methods from different threads and I get an error when trying to get a new copy of the JNIEnv pointer... the code I'm using is below and is called in each method: ``` JNIEnv* GetJniEnvHandle(){ ThreadInfo(); JNIEnv *envLoc; //if(Thread::CurrentThread->IsBackground || Thread::CurrentThread->IsThreadPoolThread) jint envRes = vm->GetEnv((void**)&envLoc, JNI_VERSION_1_4); if(envRes == JNI_OK){ if(ThreadId != Thread::CurrentThread->ManagedThreadId) jint res = vm->AttachCurrentThread((void**)&envLoc, NULL); }else{ Log("Error obtaining JNIEnv* handle"); } return envLoc; } ``` The JVM has already been instantiated and this (and other methods) run when being called from the main/initial thread. When I get a value for envRes it holds a -2 when in a sub-thread.

Original source