Why Android Runtime#LoadLibrary0 adapt with lock「Draft」

code · 2022-10-14
As we all know , the java runtime in android framework is "REWRITE" by
google developers.

we can see many of method implementation in Android Java Runtime DO NOT same as Oracle JDK or Open JDK.

Recently , I found that Runtime#loadLibrary0 method is adapt with 「Synchronize」;

which will cause ANR in many Scene of Native library load.

For example:
//WIP flow chart here

BackGround Thread start  → System.loadLibrary("") 

MainThread → wait → System.loadLibrary("")

If BackGround Thread hold lock for a long time (such as load a huge library file); MainThread will block and wait until BackGround Thread load finish; which cause ANR.

many case online;

for deal this issue , we should find out why that Runtime#loadLibrary0 in Android platform implementation adapt with Synchronize.

In Open JDK the method implementation is :

https://github.com/openjdk/jdk/blob/dfacda488bfbe2e11e8d607a6d08527710286982/src/java.base/share/classes/jdk/internal/loader/NativeLibraries.java#L182

the purpose of lock ”loadedLibraryNames“ is prevent cache fail or double-load of native library。

In Android platform ,implementation shows:

https://cs.android.com/android/platform/superproject/+/master:libcore/ojluni/src/main/java/java/lang/Runtime.java;drc=b0193ccac5b8399f9b5ef270d102b5a50f9446ab;bpv=1;bpt=1;l=1041?q=loadLibrary0&gsn=loadLibrary0&gs=kythe%3A%2F%2Fandroid.googlesource.com%2Fplatform%2Fsuperproject%3Flang%3Djava%3Fpath%3Djava.lang.Runtime%238f2e2901e98f19354082701a02fdce828b432d967e6845f6983c0fe061be5516&gs=kythe%3A%2F%2Fandroid.googlesource.com%2Fplatform%2Fsuperproject%3Flang%3Djava%3Fpath%3Djava.lang.Runtime%23d6a7908122c433e45aafe6d721fdec4ba2792519e8831d58e6937baff89f5d7e

Android
Theme Jasmine by Kent Liao