Android ClassLoader memory leak Android ClassLoader memory leak android android

Android ClassLoader memory leak


First, lets sort out the terminology here.

Is it a native library with JNI bindings that you want to load? That is, a file with the suffix .so that is implemented in C/C++ using the Android NDK? That is usually what we refer to when we talk about native library. If this is the case, then the only way to solve this is to run the library in separate process. Easiest way to do this is to create an Android service where you add android:process=":myNativeLibProcess" for the entry in the manifest. This Service will then call System.loadLibrary() as usual and you bind to the Service from your main process using Context.bindService().

If it is a set of Java classes inside a JAR file, then we are looking at something else. For Android, you need to create compile your library code into a DEX file that is placed into a JAR file and loaded using a DexClassLoader, similar to what you've done in your code. When you want to unload the library, you need to release all the references to the instances you've created AND the class loader used for loading the library. This will allow you to load a new version of the library later on. The only problem with this is that you won't reclaim all the memory used by the unloaded library on devices with API level 19 and lower (i.e., Android versions using Dalvik VM) because class definitions are not garbage collected. For Lollipop and later, the new VM will also garbage collect class definitions, so for these devices this will work better.

Hope that helps.


May be you can find answers here

I am not sure that is this you are looking for but it gives actual library deallocating method in JVM.