Search code examples
multithreadingjava-native-interfacethread-safety

Does the JVM serialize calls to JNI_OnLoad and JNI_OnUnload?


Suppose I have a C library (libcurl or opens, say) that requires an initialization function that is not thread-safe. I can initialize it in JNI_OnLoad but I could potentially race against other JNI libraries that call the initialization function. Does the JVM guarantee that this can't happen?


Solution

  • No, JVM does not have a mutex for calling JNI_OnLoad for different native libraries.

    On the other hand, JVM does guarantee that JNI_OnLoad will be called only once, so if more than one thread of your Java code loadLibrary() for the same library, then there will be no race problems.