Skip to content

Obtaining JNIEnv

Eugene Gershnik edited this page Oct 9, 2021 · 4 revisions

Every operation in JNI requires usage of JNIEnv object. Most of the time this is not a problem: JNIEnv * is passed to any native method and can be propagated from there. On occasion, however, you might not have it handy. Some common situations include writing destructors which cannot have parameters (you can work around it by storing JNIEnv * in the class but that introduces its own problems since JNIEnv is thread specific), operating on a non-Java thread and being called from portable code that has no notion of JNIEnv. Raw JNI provides various methods to obtain JNIEnv which are somewhat cumbersome to use. With SimpleJNI you can always get current JNIEnv * by calling

JNIEnv * env = jni_provider::get_jni();

It operates as follows:

  • If the thread already has JNIEnv attached it will be returned.

  • Otherwise the thread is attached to Java as daemon and the resulting JNIEnv* is returned.
    Why attach as daemon? The expectation that if you call this method to obtain JNIEnv from a non-Java thread you are unlikely to wish it to be joinable from Java. If you do want to manually add a non daemon native thread to Java you should manually do so deliberately, not as a side effect of obtaining JNIEnv

    Note that the thread will be automatically detached on its exit if it was attached by SimpleJNI. You do not need to add any special handling of your own to do so.