MATLAB: Am I unable to clear Java native libraries from MATLAB

jniMATLAB

I am developing Java classes that use native libraries. After several compile-debug cycles where I use "clear java" to purge the classes, I receive the following error when loading the newest version of my class:
Warning: A Java exception occurred trying to load the MatrixDriver class:
Java exception occurred:
java.lang.UnsatisfiedLinkError: Native Library D:\Work\jni\jnimatrixdriver.dll already loaded in another classloader
at java.lang.ClassLoader.loadLibrary0(Unknown Source)
at java.lang.ClassLoader.loadLibrary(Unknown Source)
at java.lang.Runtime.loadLibrary0(Unknown Source)
at java.lang.System.loadLibrary(Unknown Source)
at MatrixDriver.<clinit>(MatrixDriver.java:86)
> In repro at 1
??? No constructor MatrixDriver with matching signature found
Error in ==> repro at 1
j = MatrixDriver('bar')

Best Answer

This is due to the behavior of the Java Virtual Machine, which does not clear native libraries immediately.
If the objects associated with the JAR files are no longer in use, see the solutions listed below about forcing Java garbage collection.
<http://www.mathworks.com/matlabcentral/answers/99329-how-can-i-request-java-garbage-collection-in-the-java-virtual-machine-jvm-in-matlab-7-3-r2006b>
For more information on this behavior, refer to the Java documentation regarding unloading native libraries:
<https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/invocation.html#JNI_OnUnload>