2

Anyone who has ever worked with Android Studio knows that it has a very helpful code linting capacity that helps programmers avoid common anti-patterns and mistakes.

Such a system is sometimes annoying however, and in this particular case I think it's just being that.

I have a AsyncTask like the follwing

class MyAsyncTask extends AsyncTask<Void, Void, MyDataType> {
    private Context context;

    MyAsyncTask(Context _context) {
        context = _context;
    }

    @Override
    protected void onPreExecute() {
        // Show a progress dialog or something
        // to indicate that we're doing some work
        // here.
    }

    @Override
    protected MyDataType doInBackground(Void... args) {
        return generateData(); // returns `MyDataType` of course
    }

    @Override
    protected void onPostExecute(MyDataType data) {
        // Deliver the data and then
        context = null;
    }            
}

And of course, Android Studio is kindly telling me that the context field leaks a Context object.

My questions is,

  • is this really leaking the Context object? or,
  • is context = null; guaranteed to run and thus there is no leak?

This is different than Warning: This AsyncTask class should be static or leaks might occur because this is NOT A non-static inner class of a Context like in that case.

note: I am not a Java programmer, and I don't understand garbage collection very well. I have mostly worked with c and there I know how memory is managed. Garbage collected languages make me uncomfortable because I don't know how this "garbage collection" occurs.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
  • *is this really leaking the Context object?* yes, it is .... *is context = null; guaranteed to run and thus there is no leak?* no, because nothing guarantee time of that call – Selvin Jan 15 '18 at 14:42
  • 2
    Possible duplicate of [Warning: This AsyncTask class should be static or leaks might occur](https://stackoverflow.com/questions/44309241/warning-this-asynctask-class-should-be-static-or-leaks-might-occur) – Justcurious Jan 15 '18 at 14:47
  • 1
    @Justcurious I really don't think this is a duplicate. THIS IS NOT A *non-static inner class*. So it's clearly a different question. In this case I am passing a `Context` object. In that case there is no solution like the one suggested [here](https://stackoverflow.com/a/48265208/1983495), for example. – Iharob Al Asimi Jan 15 '18 at 15:01

1 Answers1

7

Yes it is leaking of Context, because your Context object can't be garbage collected before your AsyncTask wasn't terminated. doInBackground() method can proceed some large operation and before terminating your Context will be still alive. Good practice to wrap your Context object into WeakReference so if this object can be accessed only by WeakReference's it will be collected.

Anton Kazakov
  • 2,740
  • 3
  • 23
  • 34