Java – Understand memory leaks in Android applications

Understand memory leaks in Android applications… here is a solution to the problem.

Understand memory leaks in Android applications

I’m new to Java programming and have a lot of C++ experience, and I’m reading an article about how references can cause Android app memory leaks. This explanation saddens me. In Lesson 2, it says:

The point is, the Activity doesn’t know that the lifespan of SomeObject will end when the instance of the Activity ends. If that object remains in memory, it will hold that Activity in memory as well […].

As I see (probably wrong; Please correct me), when the activity ends, SomeObject is destroyed (assuming no other references to it exist). The activity references SomeObject, not the other way around. I don’t understand why anything is leaked here, let alone the entire activity.

Solution

This has to do with the fact that they are creating anonymous classes for EventListener.

public void onResume() {
    super.onResume();

SomeObject object = new SomeObject();

object.setSuccessListener(new EventListener<Boolean>() {
        public void onEvent(Boolean response) {
            Log.d(TAG_NAME, "Valid response? " +response);
        }
    });

SomeObjectManager.getSingleton().addObject(object);
}
  • Make it clear that this is in the activity
    onResume()。

  • Anonymous classes (as well as non-static inner classes) have an implicit reference to the classes around them. So in this case, the EventListener has a reference to the activity itself.

  • Therefore, SomeObject has a reference to the

  • activity because it has a reference to the anonymous class that implements the EventListener.

This is the text before the quote you quoted in the question:

For instance, in the example above: we’ve attached a reference to our
Activity instance to some object, presumably persistent, and in a
manager somewhere. The point is…

Therefore, the

SomeObjectManager class, which does not disappear when the activity is destroyed, holds a reference to SomeObject, and SomeObject holds a reference to EventListener, which in turn references an activity.

So when you say:

As I see it (probably wrong; please correct me), when the activity
ends, SomeObject is destroyed (assuming no other reference to it
exists). The activity references SomeObject, not the other way round.

The flaw in this logic is that SomeObject does reference the activity through the EventListener.

Does this help?

Related Problems and Solutions