Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does an Android applications VM exit?

I was wondering when does an applications VM exit for an Android application?

The reason I am asking I is that I was thinking about when any stray threads or un-nullified singleton references would be cleaned up, which in my mind is when the process is killed or when the VM exits.

I was under the impression that when onDestory() on all open Activities has been called then the VM would exit, or if the app was in the background and had to be killed due to memory constraints the VM would be killed (along with the process).

I guess my questions are:

  1. Are my assumptions about when the VM is exited correct?
  2. Will this ensure clean up of any stray threads and un-nullified singleton self-references?
like image 383
Dori Avatar asked Feb 28 '11 12:02

Dori


2 Answers

I was wondering when does an applications VM exit for an Android application?

Arguably, it doesn't exit. The whole process is terminated. That will happen sometime after there are no more running components. How long your process will stick around depends on the amount of RAM on the phone, what else is going on, etc.

I was under the impression that when onDestory() on all open Activities has been called then the VM would exit

There may be a delay between the last component (e.g., activity) being destroyed and the process being terminated.

or if the app was in the background and had to be killed due to memory constraints the VM would be killed (along with the process).

Android's VM can return RAM to the OS, so Android destroys activities, not processes, when RAM is tight. Now, if Android destroys all activities in a process, it may terminate the process as well.

Will this ensure clean up of any stray threads and un-nullified singleton self-references?

Those will go away when the process is terminated. However, since you don't know how long that will be, please do not leak threads.

like image 137
CommonsWare Avatar answered Sep 28 '22 04:09

CommonsWare


I hope Android closes the entire JVM and does not trust app code to clean with no bugs. I would appreciate that behavior as a user.

However you should clean up thoroughly in the onDestroy callback. Use java.util.concurrent classes for easy thread/task management.

like image 36
Tonny Avatar answered Sep 28 '22 05:09

Tonny