Skip to content

Commit

Permalink
Use atomic flag if the native library is loaded or not
Browse files Browse the repository at this point in the history
Hopefully addresses #295
  • Loading branch information
luben committed Dec 22, 2023
1 parent a3c3d7d commit c776e15
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions src/main/java/com/github/luben/zstd/util/Native.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import java.lang.UnsatisfiedLinkError;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.atomic.AtomicBoolean;

public enum Native {
;
Expand Down Expand Up @@ -47,7 +48,7 @@ private static String resourceName() {
return "/" + osName() + "/" + osArch() + "/" + libname + "." + libExtension();
}

private static boolean loaded = false;
private static AtomicBoolean loaded = new AtomicBoolean(false);

/**
* Tell the library to assume the native library is already loaded.
Expand All @@ -56,11 +57,11 @@ private static String resourceName() {
* zstd-jni to not attempt loading it again.
*/
public static synchronized void assumeLoaded() {
loaded = true;
loaded.set(true);
}

public static synchronized boolean isLoaded() {
return loaded;
return loaded.get();
}

private static void loadLibrary(final String libName) {
Expand All @@ -86,7 +87,7 @@ public static synchronized void load() {
}

public static synchronized void load(final File tempFolder) {
if (loaded) {
if (loaded.get()) {
return;
}
String resourceName = resourceName();
Expand All @@ -95,15 +96,15 @@ public static synchronized void load(final File tempFolder) {
if (overridePath != null) {
// Do not fall back to auto-discovery - consumers know better
loadLibraryFile(overridePath);
loaded = true;
loaded.set(true);
return;
}

// try to load the shared library directly from the JAR
try {
Class.forName("org.osgi.framework.BundleEvent"); // Simple OSGI env. check
loadLibrary(libname);
loaded = true;
loaded.set(true);
return;
} catch (Throwable e) {
// ignore both ClassNotFound and UnsatisfiedLinkError, and try other methods
Expand All @@ -115,7 +116,7 @@ public static synchronized void load(final File tempFolder) {
// It also covers loading on Android.
try {
loadLibrary(libnameShort);
loaded = true;
loaded.set(true);
return;
} catch (UnsatisfiedLinkError e) {
UnsatisfiedLinkError err = new UnsatisfiedLinkError(e.getMessage() + "\n" + errorMsg);
Expand Down Expand Up @@ -163,7 +164,7 @@ public static synchronized void load(final File tempFolder) {
throw err;
}
}
loaded = true;
loaded.set(true);
} catch (IOException e) {
// IO errors in extracting and writing the shared object in the temp dir
ExceptionInInitializerError err = new ExceptionInInitializerError(
Expand Down

0 comments on commit c776e15

Please sign in to comment.