Question

I have an android application using multiple threads (e.g. ui thread an networking thread). Now I want both threads to call native functions. Also some native functions will call java functions.

For this a JNIEnv* is required, which differs from thread to thread. But I assume that calling GetEnv() is pretty inefficient.

Is there a way to cache the JNIEnv*s for each thread and then determine, in which thread we are on (in the native function) to use the correct cached JNIEnv*?

Was it helpful?

Solution

You CANNOT cache the JNIEnv and should be using AttachCurrentThread() on the cached JVM*. If the native thread is already attached I believe this function is equivalent to a NOOP.

if ((*jvm)->AttachCurrentThread(jvm, (void **)(&env), NULL) == JNI_OK) {
   ....
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top