Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

should I use setDaemon() in android?

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 ?

like image 200
Tomer Mor Avatar asked Oct 17 '12 08:10

Tomer Mor


People also ask

When would you use a daemon thread?

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.

Why do we need daemon thread?

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.

What does thread setDaemon do?

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.

Why JVM terminates the daemon thread if there is no user thread?

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.


2 Answers

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.

like image 121
full.stack.ex Avatar answered Nov 08 '22 23:11

full.stack.ex


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.

like image 35
Nikolay Elenkov Avatar answered Nov 08 '22 23:11

Nikolay Elenkov