From 1af4590a74b415f4b8fa21f535638717ed86a734 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 6c938d8d41a..eba076259cb 100644 --- a/jcl/src/java.base/share/classes/java/lang/System.java +++ b/jcl/src/java.base/share/classes/java/lang/System.java @@ -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; + } + } } /**