Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage Collection of Activities

If I am not mistaken, Activity objects are never destroyed from memory, they are always there until the process is killed. So calling finish() or Android operating system destroying your Activity doesn't mean it's destroyed in memory but only means it's now in 'destroyed state' (unofficial name).

To demonstrate, I did override finalize method of my activity and then used System.gc() from a button click event of another activity. I see that finalize method of my activity is being called. If activity objects can't be destroyed while the process is running, how can activity be garbage collected?

like image 546
Insignificant Person Avatar asked Oct 12 '15 18:10

Insignificant Person


2 Answers

If there is no more reference to the activity then it gets Garbage-Collected - but leaking a activity is really easy - that said there is now a really good tool to find Activity leaks: https://github.com/square/leakcanary Also an Activity is only GCed after onDestroy() was called - not directly after finish() - hence your measurement is not working

like image 103
ligi Avatar answered Oct 10 '22 02:10

ligi


Each Activity's process is kept in memory until the space is needed or the user forcibly removes it from a process manager like the recents list (holding the home/middle button).

This is the MRU cache pattern. There won't be much left of the Activity after it has exited with finish() and/or onDestroy but the JVM required considerable setup and so is retained solely on the premise that if it was used before it is expected to be needed in future. Unless you need the memory for something else.

like image 30
John Avatar answered Oct 10 '22 03:10

John