File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Threads and Synchronization and the fly likes Daemon threads & non daemon Threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Daemon threads & non daemon Threads" Watch "Daemon threads & non daemon Threads" New topic

Daemon threads & non daemon Threads

Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
what is a daemon thread ? whats the difference between the daemon thread & non daemon thread?
I just want the explanation.
Frank Carver

Joined: Jan 07, 1999
Posts: 6920
The strict difference is that a daemon thread is one which won't prevent the program from ending. This may not be a very useful way to describe the difference, though, so here's an example:
Imagine a Java application. It starts off with just one thread, the "main" thread which runs the main method. This is a regular (non-daemon) thread. Now imagine again that the program starts another thread which sits in a loop doing something. If the new thread is a regular (non-daemon) thread, it will prevent the program from finishing when "main" ends, and keep going forever!

Now, this isn't always what is required. Sometimes you want to end this "background" processing when the program finishes. To do this, you can mark threads as daemon threads. Daemon threads don't prevent the program from ending, but stop when the main thread, stops:

Try running the two different classes above, and see how the
output is different.
A classic example of a daemon thread is the garbage collector thread found in many Java Virtual Machines. It needs to run continuously while any other threads are running, but should not prevent the program from exiting. When the program exits, there is no more need for a garbage collector.

Read about me at ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
prasad bh

Joined: Apr 25, 2000
Posts: 1
Daemon thread is a thread, which runs only when it is invoked to do the task. It is a thread which has lower priority and if a higer priority thread comes, Daemon thread's execution is stopped and resources are given to higer one. for ex: garbage collection thread.
Prasad Bh.
I agree. Here's the link:
subject: Daemon threads & non daemon Threads
jQuery in Action, 3rd edition