Friday 15 May 2015

Daemons in Java

 So far, you've been learning about threads that operate within the context of a parent program. Java provides support for another type of thread, called a daemon thread, that acts in many ways like an independent process. Unlike traditional threads, daemon threads belong to the runtime system itself, rather than a particular program. Daemon threads are typically used to manage some type of background service available to all programs. The garbage collection thread is a perfect example of a daemon thread; it chugs along without regard to any particular program performing a very useful service that benefits all programs.
You can set a thread as a daemon thread simply by calling the setDaemon method, which is defined in the Thread class, and passing true:
thread.setDaemon(true);
You can query a thread to see if it is a daemon thread simply by calling the isDaemon method, which is also defined in the Threadclass:
boolean b = thread.isDaemon();

The Java runtime interpreter typically stays around until all threads in the system have finished executing. However, it makes an exception when it comes to daemon threads. Because daemon threads are specifically designed to provide some type of service for full-blown programs, it makes no sense to continue to run them when there are no programs running. So, when all the remaining threads in the system are daemon threads, the interpreter exits. This is still the same familiar situation of the interpreter exiting when your program finishes executing; you just may not have realized there were daemon threads out there as well. 

No comments:

Post a Comment