Android memory leak logic

Usually in C ++, what a memory leak if we allocated an object, for example

Obj c = new Obj();

then if we do

c = b; (example)

we lose the pointer to the object cthat the memory leak.

Question:

But on android, the garbage collector collects an object when there are no pointers pointing to them. So why is there a memory leak after that?

Update

All answers indicate that links to unused objects are retained, causing a memory leak. It's right. But this is the only reason for the memory leak. Holding pointers will be released when activity is completed, if it is not static. There are bitmaps and other objects of hunger in memory, do not cause any problems in this

+3
source share
5 answers

, , . , , -.

, , , OOM.

+1

Android/Java

  • / , .

  • , .

, most common ones.

+1

, " ". - , , , , , . .

private static Drawable background;

@Override
protected void onCreate(Bundle state) {
  super.onCreate(state);

  TextView label = new TextView(this);

  background = getDrawable(R.drawable.large_bitmap);

  label.setBackgroundDrawable(background);

  setContentView(label);
}

TextView ,

TextView

,

, , . , , , - , .

.

+1

, (Activity, Service ..) , .

: :

public class Helper {

    private static Context mContext;

    public Helper(Context context){

        mContext = context;
    }

    public static void methodDoesSomething(){

        ...
    }
}

, , :

public class Helper {

    public static void methodDoesSomething(Context context){
        ...
    }
}

Android - , , , , .

+1

: , . , , , , , . Unibus Garbage Collector, , , , .

. , , , , . , , . Context . .

There are solutions for this, besides the obvious ones (free objects, when you finish, etc.). In Java there SoftReferences, WeakReferencesand others. These objects are containers that tell the garbage collector that they prefer to be emptied after not using them or other links pointing to them. Therefore, you are helping the GC know what should be released. They are dangerous at some point in Android environments, because applications are limited to too 16 MB of heap, and therefore WeakReferencecan be built too quickly. You need to check if the object is saved.

+1
source

All Articles