Tuesday, June 23, 2009

Daemon Thread and User Threads

In java we have two type of Threads : Daemon Thread and User Threads. Generally all threads created by programmer are user thread (unless you specify it to be daemon or your parent thread is a daemon thread). User thread are generally meant to run our programm code. JVM doesn't terminates unless all the user thread terminate.

On the other hand we have Daemon threads. Typically these threads are service provider threads. They should not be used to run your program code but some system code. These thread run paralley to your code but survive on the mercy of the JVM. When JVM finds no user threads it stops and all daemon thread terminate instantly. Thus one should never rely on daemon code to perform any program code.

For better understanding consider a well known example of Daemon thread : Java garbage collector. Garbage collector runs as a daemon thread to recalim any unused memory. When all user threads terminates, JVM may stop and garbage collector also terminates instantly.


--------------------

daemon threads are created by the JVM unlike normal threads which are created by the user.
The daemon threads provides services to the user-created threads and they run in the background.
Hence to set them u have to write threadname.setDaemon(true) and to check whether a thread is a daemon thread or not you write isDaemon().

No comments:

Post a Comment