Why does this run out of memory? Shouldn't the Activities be released?

88 views Asked by At

A project with only the following two activities will throw an OutOfMemoryError. Why does this happen? Shouldn't the older activities on the stack be released when memory is nearing the limit of the heap?

public class MainActivity extends Activity
{
    @Override
   protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startActivity(new Intent(getApplicationContext(), MemoryActivity.class));
    }
}

public class MemoryActivity extends Activity
{
    int[] testMem = new int[750000 * 3];

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startActivity(new Intent(getApplicationContext(), MainActivity.class));
    }

}
3

There are 3 answers

1
queencodemonkey On BEST ANSWER

It seems the consensus is that the documentation is out-of-date or misleading, because if an activity's process is in the foreground, that activity will not be killed even if it is stopped. An activity will be killed as part of its entire process being killed.

Please check out this question, answer by Dianne Hackborn, and discussion: Android app out of memory issues - tried everything and still at a loss

0
Nathan Vance On

I think this is more of a question of stacks and heaps. Activities are pushed onto a stack, in android called the back stack. In a stack, elements below the top element are unaccessable until the top element has been popped. In the case of your code, this never happens. I would be curious to know (but haven't tested) if removing your array from the MemoryActivity would result in a stack overflow rather than the OutOfMemoryError ;)

If spawning new activities were implemented using a heap rather than a stack (and it's not), then android could theoretically free up memory as you said. In fact, this is exactly how Java's garbage collecter works.

0
Harsh Middha On

its a infinite loop , you are starting MemoryActivity from MainActivity and again you are starting MainActivity from MemoryActivity this loop continues.

A -> B -> A ->B -> A -> B .......