Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

Is this class leaking a context object?

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,

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.

Upvotes: 2

Views: 1488

Answers (1)

Anton Kazakov
Anton Kazakov

Reputation: 2774

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.

Upvotes: 7

Related Questions