Understanding memory leaks in an Android app

I am new to Java programming, with a lot of experience in C ++, and I read about how links can lead to memory leaks in Android applications. This explanation puzzled me. Lesson 2 says:

The fact is that Activity does not know that SomeObject will expire when an Activity instance ends. If this object remains in memory, it will also save this activity in memory [...].

As I see it (maybe wrong, please correct me), when the action ends, it SomeObjectwill be destroyed (provided that there is no other reference to it). The action is referenced SomeObject, not the other way around. I do not understand why something is leaking here, not to mention all the activities.

+4
source share
3 answers

This is because they create an anonymous class 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);
}
  • He explicitly stated that this is done in onResume ().

  • Anonymous classes (as well as non-static inner classes) have an implicit reference to the surrounding class. Therefore, in this case, the EventListener has a link to the Activity itself.

  • Therefore, SomeObject has a reference to Activity, because it has a reference to the Anonymous class, which implements EventListener.

, :

, : weve , , -. , ...

, SomeObjectManager, , SomeObject, SomeObject EventListener, , , Activity.

, :

(, , , ), end, SomeObject ( ). SomeObject, .

, SomeObject EventListener.

?

+2

: ?

, :

Log.d(TAG_NAME, "Valid response? "+response);

, 'this'. , this$0.

, :

objectFromBefore.setSuccessListener(null);

, :

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

SomeObjectManager.getSingleton().addObject(object);

:

SomeObjectManager → singleton → listofObjects → object

:

object- > successListeners- > anonymous EventListener- > this $

this $ - , .

+2

, Activity. Android, , ( ) . , , , , .

Activity

1) // (null)// Activity.

2) , , . ( )

3) . ( Handlers - )

, ,

1) (null)//

2) , , , .

3) , WeakReferences

4) , , .

,

1) , .

2) ( , .)

3) , Android , , .

Android Studio Device Monitor, hprof-conv Eclipse Memory Analyzer. , , , Activity, - Monitor Monitor, , . , . hprof-conv , , MAT, MAT.

MAT. .

+2

All Articles