Thursday, May 29, 2008

Threads and Daemon Threads in Java.


A thread represents an execution environment. It's quite similar to a process with the difference that threads within the same process share much of the same state including the address space and other open I/O resources of the process. The Java Virtual Machine allows multithreading which means that more than one thread can continue to execute concurrently in the same process.

Threads are used to execute a task and based on the importance of the task we can assign priority to the thread executing it. Obviously the threads having a higher priority will be given preference over those threads which are having a relatively lower priority.

Daemon Threads

There may be cases when you may like to have certain periodic and routine tasks running as background threads. You can set any thread as daemon thread for that purpose by using the setDaemon() method. This ensures that this thread will be killed and discarded only when all other threads of the application have already exited. The Java Interpreter thread continues to run until all the non-daemon threads running in that JVM have exited. If it finds that the only active threads are daemon thraeds, then the Java Interpreter thread exits. Example of creating a daemon thread in Java:-

public class BackgroundThread extends Thread{


setDaemon(true); //setting the thread as a daemon thread
start(); //scheduling the thread for execution


public void run() {

//the code which is required to be run under this thread


When does a thread stop its execution?

On start up of a JVM, only a single non-daemon thread exists. This thread eventually calls the main() method of a designated class. All the threads running in a JVM keep on executing until one of the following two cases occur:-

  • The security manager has approved the exit operation - this happens when the exit method of the class Runtime has been called and the underlying security manager is okay with the call.
  • The non-daemon thread has died in the JVM - this happens when the non-daemon thread has either returned from its run method after completing the designated task or throws an exception which is not handled in the run method and hence propagates beyond that method.



Javin @ FIX Protocol Tutorial said...

Daemon thread also inherit daemon property from parent thread. so if a daemon thread is used to create another thread then it would be by default daemon.

How to setup remote debugging in Eclipse

Javin Paul said...

Main difference between daemon and non daemon thread is that in case of former JVM doesn't wait for finishing execution. see here for more difference between daemon and non daemon threads in java