When a Fragment is replaced and put in the back stack (or removed) does it stay in memory?

Take a look at this: BackStackRecord.Op.fragment

That is how fragments are stored in the back stack. Note the live reference, neither WeakReference nor SoftReference are used there.

Now this: FragmentManagerImpl.mBackStack

That is where manager stores the back stack. Simple ArrayList, also, no WRs or SRs.

And finally this: Activity.mFragments

That is the reference to the fragment manager.

GC can only collect objects that have no live references (are not reachable from any thread). That means, until your Activity is destroyed (and so, FragmentManager reference is gone), GC will not be able to collect any of the Fragments in the back stack.

Note that when Activity is destroyed and retains state (like when you turn the device to landscape mode), it doesn’t retain actual Fragment objects in the stack, only their states – Fragment.FragmentState objects, i.e. actual fragments in the back stack are re-created every time activity gets re-created with retained state.

Hope this helps.

PS So, in short: Yes, you can run out of memory by adding Fragments to back stack as well as by adding too many views to view hierarchy.

UPD Considering your example, F will stay in memory until C is killed. If C is killed and then resurrected with different configuration – F will be destroyed and reincarnated in a different object as well. So, F‘s memory footprint is around until C loses state or back stack is cleared.

Leave a Comment