Search code examples
java-native-interface

How does JNI function (isSameObject) implement in native code?


I know the code below can compare whether obj1 and obj2 share with a same reference:

(*env)->IsSameObject(env, obj1, obj2)

Actually, I try to check these two objects' ref directly like:

jboolean result = (obj1 == obj2);

But the result is different from the result of "IsSameObject".

I was wondering how does IsSameObject implement, and why the result of (obj1 == obj2) is different?


Solution

  • JNI handles are not direct pointers to Java objects. Java objects can move across Heap during garbage collection. Their memory addresses may change, but JNI handles must remain valid.

    JNI handles are opaque to user, that is, the implementation of handles is JVM-specific. JNI functions like IsSameObject provide the abstraction layer.

    In HotSpot JVM handles are pointers to mutable object references.
    IsSameObject performs something like

    return obj1 == obj2 || obj1 != NULL && obj2 != NULL && *(void**)obj1 == *(void**)obj2;
    

    but atomically in respect to object relocation.