I'm creating a service Thread for my application, this thread will perform background tasks, and therefore it'll be usage only if my Main thread is running.
So should I declare it as a Daemon ?
3. Uses of Daemon Threads. Daemon threads are useful for background supporting tasks such as garbage collection, releasing memory of unused objects and removing unwanted entries from the cache.
Daemon threads are used for background supporting tasks and are only needed while normal threads are executing. If normal threads are not running and remaining threads are daemon threads then the interpreter exits. When a new thread is created it inherits the daemon status of its parent.
Thread. setDaemon(true) makes a Thread daemon but it can only be called before starting Thread in Java. It will throw IllegalThreadStateException if corresponding Thread is already started and running.
JVM terminates itself when all user threads (non-daemon threads) finish their execution, JVM does not care whether Daemon thread is running or not, if JVM finds running daemon thread (upon completion of user threads), it terminates the thread and after that shutdown itself.
On Android, it's better to make sure you manage your threads explicitly. Tell them when to terminate.
See a related discussion here. They didn't find a solution, and observed long-living threads instead:
What hooks do we have in order to do worker thread termination on application exit
Note that standard Java shutdown hooks are not guaranteed on this platform:
http://developer.android.com/reference/java/lang/Runtime.html#addShutdownHook%28java.lang.Thread%29
So, instead of relying on an (undocumented?) belief that Android will properly kill your VM anyway and guessing on daemon/not daemon, it seems to be better to control the threads.
Not really. Android doesn't have a main()
methods for apps and they don't exit, but are managed by the system. If it decides to kill your app to free resources, it (most probably) won't care if you have daemon threads or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With