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 Sep 30, 2024
1 parent ef7bb17 commit 5d5b4d9
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 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,28 @@ 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 */
}
}
}

/**
Expand Down

0 comments on commit 5d5b4d9

Please sign in to comment.