Skip to content

Commit

Permalink
Attempt to reload the library in case of UnsatisfiedLinkError
Browse files Browse the repository at this point in the history
When an UnsatisfiedLinkError is thrown because the library was already
loaded in another classloader, run gc() to unload the unreachable
classloaders, and reload the library again.

Signed-off-by: Jason Feng <[email protected]>
  • Loading branch information
JasonFengJ9 committed Oct 1, 2024
1 parent 94886ed commit 1af4590
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions jcl/src/java.base/share/classes/java/lang/System.java
Original file line number Diff line number Diff line change
Expand Up @@ -1152,10 +1152,30 @@ public static void loadLibrary(String libName) {
smngr.checkLink(libName);
}
/*[IF JAVA_SPEC_VERSION >= 15]*/
ClassLoader.loadLibrary(getCallerClass(), libName);
Class<?> callerClass = getCallerClass();
/*[ELSE]*/
ClassLoader.loadLibraryWithClassLoader(libName, ClassLoader.callerClassLoader());
ClassLoader callerClassLoader = ClassLoader.callerClassLoader();
/*[ENDIF] JAVA_SPEC_VERSION >= 15 */
try {
/*[IF JAVA_SPEC_VERSION >= 15]*/
ClassLoader.loadLibrary(callerClass, libName);
/*[ELSE]*/
ClassLoader.loadLibraryWithClassLoader(libName, callerClassLoader);
/*[ENDIF] JAVA_SPEC_VERSION >= 15 */
} catch (UnsatisfiedLinkError ule) {
String errorMessage = ule.getMessage();
if ((errorMessage != null) && errorMessage.contains("already loaded in another classloader")) { //$NON-NLS-1$
// attempt to unload the classloader, and retry
gc();
/*[IF JAVA_SPEC_VERSION >= 15]*/
ClassLoader.loadLibrary(callerClass, libName);
/*[ELSE]*/
ClassLoader.loadLibraryWithClassLoader(libName, callerClassLoader);
/*[ENDIF] JAVA_SPEC_VERSION >= 15 */
} else {
throw ule;
}
}
}

/**
Expand Down

0 comments on commit 1af4590

Please sign in to comment.