esuslogo
 [To advertise Java(tm) Events here, contact joris@esus.com!]
banner

Java™
by example!






New @ Esus.com


  gb  In-house search engine for better results!

  gb  Get updates with the esus.com
newsletter!









  Home 
 Browse Categories 
 Ask a Java Question 
 Help 
  For Java Tips & Tricks, subscribe to the esus.com newsletter!
Search Java Q&A, Links, API's:   adv 

What is a daemon thread?
There are two types of threads: user threads and daemon threads. Typically, you create user threads. A Java application will not terminate unless all user threads have finished execution, including the one that executes main() (the main thread of execution). If a thread has the daemon flag set to true, the JVM will end it regardless of whether or not it still has more work to do, if there are no more other user threads running. A user thread keeps the application from terminating. A daemon thread doesn't.

You specify a thread to be daemon by setting the daemon flag to be true, using the setDaemon method. This has to be done before the thread is started. The setDaemon method calls the method checkAccess from the System's SecurityManager and will throw a SecurityException if you are not permitted to change the daemon status.

An example of a daemon thread is the JVM's garbage collector thread.

The following two apps show the difference. The app WithoutDaemon will create a user thread that will print out 1000 numbers. WithDaemon creates a daemon thread instead and will only print out until the main execution thread reaches the end.

WithoutDaemon.java:


This code sample is only viewable to esus.com members
Login or become a member!


WithDaemon.java:


This code sample is only viewable to esus.com members
Login or become a member!




Further Information
Author of answer: Joris Van den Bogaert

Comments
Comments to this answer are only viewable by members. Login or become a member!





Terms of Service | Privacy Policy | Contact

Copyright © 2000-2003 Esus.com - All Rights Reserved 
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. Esus.com is independent of Sun Microsystems, Inc. All other trademarks are the sole property of their respective owners.