Search code examples
java-native-interface

Deleting global references in JNI


I am not sure what this means:

virtual ~Optimizer() {
    JNIEnv *env = getJNIEnv();
    env->DeleteGlobalRef(mJavaOptimizer);
    mJavaOptimizer = 0;
}

What confuses me is that we delete the global reference and then we set it to 0. Isn't deleting it enough? Why the assignment to 0 part?

Thanks


Solution

  • In this code, being in a C++ destructor, it has no practical use. It's just a programming pattern.

    In many contexts, a variable is accessible (visible) before or after it holds a valid value. During those times, it is preferable for it to hold a known value chosen so the value can be tested (a sentinel value) and/or its misuse is reliably caught in a defined way (e.g., null pointer vs bad pointer).

    Setting a variable to a standard invalid value also serves as a comment that an operation has just invalidated the previous value, which might not be obvious from a reading of the immediate code.