Louis Durand
Louis Durand

Reputation: 335

Android - Is this a memory leak? (Reference an object created in an Activity in another Activity as a static variable)

Let's say I have Activity1 that creates a simple custom object CustObject. CustObject doesn't reference any Context or similar type of object. Then, I want to pass this instance to Activity2 by setting it as a static variable in Activity2. Have a look at the corresponding code:

public class CustObject {

    private int attr;

    public CustObject(int arg) { // takes only integers and Strings
        attr = arg;
    }
}

Here's the first activity :

public class Activity1 extends Activity {

    private CustObject co;

    @Override
    protected void onCreate(Bundle b) {
        co = new CustObject(42);
    }

    public void launchActivity2() {
        Activity2.co = co;
        startActivity(new Intent(this, Activity2.class);
    }
}

And here's the second activity :

public class Activity2 extends Activity {

    public static CustObject co;

    @Override
    protected void onCreate(Bundle b) {
        // stuff
    }

    // Do operations on the co object.
}

So my thought is that when we launch Activity2, we only "leak" the co object - which is wanted - but the rest of Activity1 and its context can be garbage collected if necessary without any problems/leaks, right?

Note that I want to do it that way because, the CustObject co is likely to be changed by Activity2 and I would like these changes to be displayed automatically in Activity1 if it hasn't been killed. If it has been killed, then it works because everything will be reloaded and the changes to CustObject in Activity2 were also stored in a database.

Thank you for your help!

PS : Also, I've always wondered if launching an activity by giving "this" as context for an Intent is leaking the parent activity??

Upvotes: 0

Views: 524

Answers (1)

Vaiden
Vaiden

Reputation: 16122

So...

  1. Static vars are located in the perm-gen area. In plain English - they're all kept in a designated area in the heap. More here: static allocation in java - heap, stack and permanent generation

  2. So your Activity2.co object will not be garbage collected, regardless of either Activity1 or Activity2's state. This is not exactly a "leak", but once set - the object will occupy memory for the duration of the process' life.

  3. Android may anytime "kill" an Activity in order to free memory. Activitys are supposed to maintain their state via a savedState object. More here: https://developer.android.com/training/basics/activity-lifecycle/recreating.html

  4. So storing static objects might not be the right way to pass data between Activitys. Here is a discussion on the alternatives: How do I pass data between Activities in Android application?

Upvotes: 1

Related Questions