Search code examples
androidmemory-leakssingletonandroid-context

How to avoid memory leak here?


I'm creating a module (a group of classes to perform functionality) where I need the context object to perform some operations like secure setting read and others.

I do not like to create multiple objects for my classes which ideally is not needed in my case even so i'm doing something like this,

class MyModuleFactory {

    private static final String TAG = MyModuleFactory.class.getSimpleName();
    public Context mContext;
    private static HashMap<Context, MyModuleFactory> myInstance = new HashMap<>();

    private MyModuleFactory(Context context) {
        mContext = context;
    }

    public static synchronized MyModuleFactory getInstance(Context mContext) {
        if(mContext == null) {
            Log.i(TAG, "Context cannot be null");
            return null;
        }
        if(myInstance.get(mContext.getApplicationContext()) != null) {
            return myInstance.get(mContext.getApplicationContext());
        } else {
            MyModuleFactory myModuleFactory = new MyModuleFactory(mContext);
            myInstance.put(mContext.getApplicationContext(), myModuleFactory);
        }
    }
}

My worry here is since I'm holding the context of application here I'm afraid that I could cause memory leak - the reason is because Android can clear up application object and recreate it at anytime. So holding the context behind the application's lifecycle and not allowing to clear the context here could cause memory leak.

What is the better way to force singleton for my module here and also avoiding memory leak.


Solution

  • There won't be any memory leak if you are holding a reference to Application context. Application context lives as long as the app is running. It gets destroyed when the app is killed. In that case, even your singleton will be destroyed, so no memory leak will happen.

    Just make sure you are holding reference only to the Application context in the singleton, not Activity context.

    Check this post for detailed information:

    If you have to create a singleton object for your application and that object needs a context, always pass the application context.

    If you pass the activity context here, it will lead to the memory leak as it will keep the reference to the activity and activity will not be garbage collected.