Search code examples
androidweak-references

Android WeakReference to handle memory leakage


Please check the below code, Can we use the WeakReferences like below in Utils class to handle context memory leakage?

private static final String TAG = "Utils";
private static Utils instance;
private Context context;

public Utils(WeakReference<Context> context) {
    this.context = context.get();
}

public static synchronized final Utils getInstance(Context context) {
    if (instance == null) {
        instance = new Utils(new WeakReference<Context>(context));
    }
    return instance;
}

Solution

  • No, a WeakReference can return null at any time so it makes this kind of pointless.

    You are going to have check the WeakReference for a null every time you access it and then you will need to deal with that case by providing the context in the methods arguments, therefore eliminating the need to store a context in the fields.

    A better (but not the best) solution is to use the ApplicationContext, context.getApplicationContext(), probably the best is to pass the context into every method call.