Skip to content

Commit

Permalink
Add synchronized block to protect against race condition (#69)
Browse files Browse the repository at this point in the history
Summary:
Fixes: #60

As mentioned in issue #60 if the init method is called twice from two different threads it can result in a race condition where both threads receive false for `NativeLoader.isInitialized()`, but, when `NativeLoader.init()` is run for a second time it throws an exception.

Adding a synchronized block here ensures that only one thread will be able to query the initialisation state and trigger the initialisation at a time.

Pull Request resolved: #69

Reviewed By: oprisnik

Differential Revision: D25973362

Pulled By: wizh

fbshipit-source-id: d340bae2b8891c6f095a2560b37ded50cf20ab67
  • Loading branch information
alsutton authored and facebook-github-bot committed Jan 22, 2021
1 parent 545548d commit 17b6163
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
4 changes: 1 addition & 3 deletions java/com/facebook/soloader/SoLoader.java
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,7 @@ public static void init(Context context, int flags, @Nullable SoFileLoader soFil
isSystemApp = checkIfSystemApp(context, flags);
initSoLoader(soFileLoader);
initSoSources(context, flags, soFileLoader);
if (!NativeLoader.isInitialized()) {
NativeLoader.init(new NativeLoaderToSoLoaderDelegate());
}
NativeLoader.initIfUninitialized(new NativeLoaderToSoLoaderDelegate());
} finally {
StrictMode.setThreadPolicy(oldPolicy);
}
Expand Down
11 changes: 11 additions & 0 deletions java/com/facebook/soloader/nativeloader/NativeLoader.java
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,15 @@ public static synchronized void init(NativeLoaderDelegate delegate) {
public static synchronized boolean isInitialized() {
return sDelegate != null;
}

/**
* Perform an initialization only if {@code NativeLoader} has not already been initialized. This
* protects against race conditions where isInitialized and init are called by multiple threads
* and both threads end up trying to perform an initialization
*/
public static synchronized void initIfUninitialized(NativeLoaderDelegate delegate) {
if (!isInitialized()) {
init(delegate);
}
}
}

0 comments on commit 17b6163

Please sign in to comment.