Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer() as Daemon Vs non Daemon

Tags:

android

timer

//Creates a new Timer which may be specified to be run as a daemon thread.
Timer(boolean isDaemon)  

//Creates a new non-daemon Timer.
Timer()

When does a timer should be started as Daemon inside an android app ?

The documentation says nothing about it .

http://developer.android.com/reference/java/util/Timer.html

like image 454
tony9099 Avatar asked Oct 29 '13 14:10

tony9099


People also ask

What is difference between Daemon and non Daemon thread?

Daemon threads are low priority threads which always run in background and user threads are high priority threads which always run in foreground. User Thread or Non-Daemon are designed to do specific or complex task where as daemon threads are used to perform supporting tasks.

Is Java util Timer thread safe?

Java Timer class is thread safe and multiple threads can share a single Timer object without need for external synchronization.

How does Timer in Java work?

A Timer in Java is a process that enables threads to schedule tasks for later execution. Scheduling is done by keeping a specific process in the queue such that when the execution time comes, the processor can suspend other processes and run the task.

What is Daemon in threading?

A Daemon thread is a background service thread which runs as a low priority thread and performs background operations like garbage collection. JVM exits if only daemon threads are remaining. The setDaemon() method of the Thread class is used to mark/set a particular thread as either a daemon thread or a user thread.


1 Answers

If your application is running a user-thread (i.e. non-daemon thread) then the JVM will wait till the return of its run() method (or the thread has completed its execution) before it terminates the application. However, if your thread is set as daemon, then it instructs the JVM not to wait for the completion of its execution in case the JVM needs to close down the application (i.e. when no other user threads are running). Other than this, both types of threads are treated equally in all other aspects.

In your case, you should not set your Timer as daemon thread, until and unless you don't want its execution to hold the termination of application.

For more information, read this and this.

like image 74
waqaslam Avatar answered Sep 29 '22 02:09

waqaslam