4

Please consider the following scenario:

I have two java classes, loaded using different system class loaders. I have a native library that has a queue implemented. Both the classes will load the same library, and add elements to the queue. Is it possible? If so, will the native library implementation be shared across the two classes.?

Reji
  • 3,426
  • 2
  • 21
  • 25

1 Answers1

8

According to the JNI Specification it is not possible.

In the JDK, each class loader manages its own set of native libraries. The same JNI native library cannot be loaded into more than one class loader. Doing so causes UnsatisfiedLinkError to be thrown. For example, System.loadLibrary throws an UnsatisfiedLinkError when used to load a native library into two class loaders.

maba
  • 47,113
  • 10
  • 108
  • 118
  • The error will occur, only If I try to load the library again. right? Can I call the methods in the library, from a different class loader ? – Reji Apr 24 '13 at 12:44
  • I think one of the following paragraphs answers that slightly: *"In addition, native libraries can be unloaded when their corresponding class loaders are garbage collected"*. So this means that **if** you were to use the library across different class loaders, the native library might be unloaded which will be problematic. – maba Apr 24 '13 at 13:05
  • 1
    @maba Section 5.2 "Library and Version Management" of the JNI specification says, on the one hand: "Once a native library is loaded, it is visible from all class loaders. / Native methods can easily mix classes from different class loaders. / This breaks the name space separation offered by class loaders." On the other hand, it says: "Each class loader manages its own set of native libraries. / A native library cannot easily mix classes from different class loaders. / Name space separation based on class loaders is preserved in native libraries." Isn't this clearly contradictory? – user1494080 Oct 24 '19 at 12:04
  • @user1494080 It seems the 2nd statement is the correct one. I loaded a library in 1 classloader. Upon trying to use a native call from a different classloader, an "UnsatisfiedLinkError" is being thrown. – Ahmad Tn Aug 12 '20 at 15:45