JniHelper caching JNIEnv


looking at the latest code of cocos2d-x 3.0, I noticed that in JniHelper, the JNIEnv is being cached once and JniHelper::getEnv() will return that same pointer. Does this mean JniHelper won’t work for other threads? JNIEnv could not be shared between threads according to http://developer.android.com/training/articles/perf-jni.html#JavaVM_and_JNIEnv.

appreciate in advance.



Hi Mo, I don’t think so, from the following code, if the thread is attached to the JavaVM, the JNIEnv* is also set as its own thread local.

    // Thread not attached
    if (jvm->AttachCurrentThread(&_env, nullptr) < 0)
            LOGE("Failed to get the environment using AttachCurrentThread()");

            return nullptr;
        } else {
        // Success : Attached and obtained JNIEnv!
        pthread_setspecific(g_key, _env);
        return _env;

so we can get the JNIEnv* for different threads.