From 1210fc94cf81046bfcd5c5f02da56bab99428743 Mon Sep 17 00:00:00 2001 From: Jason Feng Date: Thu, 26 Sep 2024 17:22:05 -0400 Subject: [PATCH] Attempt to reload the library in case of UnsatisfiedLinkError 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 --- .../share/classes/java/lang/System.java | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/jcl/src/java.base/share/classes/java/lang/System.java b/jcl/src/java.base/share/classes/java/lang/System.java index 5bdf9de5da8..23b67b92d68 100644 --- a/jcl/src/java.base/share/classes/java/lang/System.java +++ b/jcl/src/java.base/share/classes/java/lang/System.java @@ -1142,10 +1142,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; + } + } } /**