Java Daemon Thread

Source: Internet
Author: User

There are two types of threads in Java: User thread, Daemon thread (daemon thread)

In a more popular example, any daemon is a nanny for all non-daemon threads throughout the JVM:

The daemon thread works as long as any non-daemon thread in the current JVM instance is not finished, and the daemon ends up working with the JVM only when the last non-daemon thread ends.
The role of Daemon is to facilitate the operation of other threads, the most typical application of the daemon is the GC (garbage collector), which is a competent guardian.

The only difference between user and daemon is that the virtual machine leaves: If the user thread is all out of operation, only the daemon thread is present, and the virtual machine exits. Because there is no guardian, Daemon has no work to do, there is no need to continue to run the program.


It is worth mentioning that the daemon thread is not only available inside the virtual machine, but the user can also set the daemon itself when writing the program. The following method is used to set the daemon thread.

[Java]View PlainCopy
    1. Thread daemontread = new Thread ();
    2. //Set Daemonthread as the daemon thread, default false (non-daemon thread)
    3. Daemonthread.setdaemon (true);
    4. //Verifies whether the current thread is a daemon thread and returns true as the daemon thread
    5. Daemonthread.isdaemon ();


Here are a few things to note:

(1) Thread.setdaemon (true) must be set before Thread.Start () or run out of a illegalthreadstateexception exception. You cannot set a running regular thread as a daemon thread.
(2) The new thread generated in the daemon thread is also daemon.
(3) Do not assume that all applications can be assigned to daemon for service, such as read-write operations or computational logic.

Because you can't know if daemon has completed the expected service task before all the user finishes. Once the user exits, it is possible that a large amount of data has not been read or written out, and the calculation task may run differently multiple times. This is devastating to the program. The reason for this result has been said: Once all the user thread has left, the virtual machine will be out of operation.

[Java]View PlainCopy
  1. The daemon thread task to complete the file output
  2. Import java.io.*;
  3. Class Testrunnable implements runnable{
  4. public Void Run () {
  5. try{
  6. Thread.Sleep (+); Daemon thread blocks after 1 seconds of running
  7. File f=new file ("Daemon.txt");
  8. FileOutputStream os=New FileOutputStream (F,true);
  9. Os.write ("daemon". GetBytes ());
  10. }
  11. catch (IOException E1) {
  12. E1.printstacktrace ();
  13. }
  14. catch (interruptedexception E2) {
  15. E2.printstacktrace ();
  16. }
  17. }
  18. }
  19. Public class testdemo2{
  20. public static void Main (string[] args) throws interruptedexception
  21. {
  22. Runnable tr=New testrunnable ();
  23. Thread thread=new Thread (TR);
  24. Thread.setdaemon (true); //Set daemon thread
  25. Thread.Start (); //Start the implementation of the sub-process
  26. }
  27. }
  28. Run Result: There is no "daemon" string in file Daemon.txt.


See, it's scary to wrap the input and output logic into the daemon thread, and the string is not written to the specified file. The reason is also very simple, until the main thread completes, the daemon is still in a 1-second blocking state. This time the main thread runs out quickly, the virtual machine exits, daemon stop service, the output operation naturally failed.

[Java]View PlainCopy
  1. Public class Test {
  2.   Public static void Main (String args) {
  3. Thread T1 = new Mycommon ();
  4. Thread t2 = new Thread (new Mydaemon ());
  5. T2.setdaemon (true); //Set as daemon thread
  6. T2.start ();
  7. T1.start ();
  8. }
  9. }
  10.   Class Mycommon extends Thread {
  11.   Public void Run () {
  12.   for (int i = 0; i < 5; i++) {
  13. System.out.println ("Thread 1" + i + "time to execute!)  ");
  14.   try {
  15. Thread.Sleep (7);
  16. } catch (Interruptedexception e) {
  17. E.printstacktrace ();
  18. }
  19. }
  20. }
  21. }

[HTML]View PlainCopy
    1. class mydaemon implements runnable {   
    2. Public void run ()  {  
    3. for  (Long i = 0; i < 9999999l; i++)  {  
    4. System.out.println ("Background line Cheng Di"  + i +  "Times execution! ");   
    5. try {  
    6. Thread.Sleep (7);   
    7. } catch  (interruptedexception e)  {  
    8. e.printstacktrace ();   
    9. }  
    10. }  
    11. }  
    12. }   


The background thread executes for the NO. 0 time!
Thread 1 executes for the NO. 0 time!
Thread 1 executes for the 1th time!
The background thread executes for the 1th time!
The background thread executes for the 2nd time!
Thread 1 executes for the 2nd time!
Thread 1 executes for the 3rd time!
The background thread executes for the 3rd time!
Thread 1 executes for the 4th time!
The background thread executes for the 4th time!
The background thread executes for the 5th time!
The background thread executes for the 6th time!
The background thread executes for the 7th time!
Process finished with exit code 0
From the above results can be seen:
The foreground thread is guaranteed to execute, and the background thread has not finished executing and exits.

In fact: The standard for the JRE to determine whether the program is finished is all the front line octave complete, regardless of the background thread state, therefore, in the use of the background county must pay attention to this problem.

Supplemental Description:
Definition: A daemon thread-also known as a "service thread"-automatically leaves when no user thread is available to serve.
Priority: The daemon thread has a lower priority to service other objects and threads in the system.
Set: The thread is set to "daemon" by Setdaemon (true), and the way a user thread is set to the
daemon is the Setdaemon method of the thread object that was used before the Threads object was created.
Example: The garbage collection thread is a classic daemon thread, and when our program no longer has any running
thread, the program will no longer generate garbage, and the garbage collector will have nothing to do, so when the garbage collection thread is the only thread left on the JVM, The garbage collection thread will automatically leave. It is always running in a low-level state for
real-time monitoring and management of recyclable resources in the system. The
Life cycle: Daemon (Daemon) is a special process that runs in the background. It is independent of the control terminal and
periodically performs some sort of task or waits for certain occurrences to be handled. That is, the
says that the daemon thread is not dependent on the terminal, but relies on the system and the system "die". The Java daemon thread is
what it looks like. The JVM exits when all the threads in the JVM are daemons, and the JVM does not exit if there is also a non-daemon thread of
or more.


Actual application Example:

In a long-connected comet server-side push technology, the message push thread is set as the daemon thread, serving the servlet user thread of Chatservlet, starting the message thread in the servlet init, and once the servlet is initialized, the server is always present. Message thread exits automatically after servlet is destroyed

The container receives a servlet request, the dispatch thread picks a worker thread from the thread pool, passes the request to the worker thread, and the thread executes the Servlet's service method. When this thread is executing, the container receives another request, and the dispatch thread also selects another worker thread from the thread pool to serve the new request. The container does not care whether the request accesses the same servlet. When the container receives multiple requests to the same servlet at the same time, the servlet's service () method executes concurrently on multiple threads.
The servlet container defaults to single-instance multithreading to handle requests, which reduces the overhead of generating servlet instances, increases response time to requests, and can be used by Tomcat in Server.xml <Connector> Element sets the number of threads in the thread pool.



Why use a daemon thread?

We know that static variables are classloader levels, and if the Web application stops, these static variables are also purged from the JVM. But the thread is at the JVM level, and if you start a thread in a web app, the thread's life cycle does not stay in sync with the Web application. In other words, even if you stop the Web app, the thread is still active. Because of this very obscure problem, many experienced developers are not quite in favor of launching threads in Web applications.

If we use the JDK timer manually (Quartz scheduler), start the timer when the Web container starts, and when the Web container is closed, the task in the timer will continue to run unless you manually close the timer!

Here's a small example to illustrate this "weird" phenomenon, where we create a timer and periodically run a task with Servletcontextlistener when the Web container starts:

[Java]View PlainCopy
  1. Code Listing Startcycleruntask: Container listener
  2. Package com.baobaotao.web;
  3. Import Java.util.Date;
  4. Import Java.util.Timer;
  5. Import Java.util.TimerTask;
  6. Import javax.servlet.ServletContextEvent;
  7. Import Javax.servlet.ServletContextListener;
  8. Public class Startcycleruntask implements Servletcontextlistener ... {  
  9. Private timer timer;
  10. public void contextdestroyed (Servletcontextevent arg0) ... {  
  11. //② This method executes when the Web container is closed
  12. System.out.println ("Web application startup off ...");
  13. }
  14. public void contextinitialized (Servletcontextevent arg0) ... {  
  15. //② automatically executes the method when the Web container starts
  16. System.out.println ("Web application Startup ...");
  17. Timer = new timer (); ②-1: Create a Timer,timer inside automatically create a background thread
  18. TimerTask task = new Simpletimertask ();
  19. Timer.schedule (Task, 1000L, 5000L); //②-2: Register a task that runs once in 5 seconds
  20. }
  21. }
  22. Class Simpletimertask extends TimerTask ... {//③ task
  23. private int count;
  24. public void Run () ... {  
  25. System.out.println ((++count) +"Execute task ..." + (new Date ()));
  26. }
  27. }


Declare this web container listener in XML: <?xml version= "1.0" encoding= "UTF-8"?>
<web-app>
...
<listener>
<listener-class>com.baobaotao.web.StartCycleRunTask</listener-class>
</listener>
</web-app>

After you deploy this web App in Tomcat and start, you'll see that the task executes every 5 seconds.
After running for a period of time, log in to the Tomcat admin backend and close the corresponding Web application (CHAPTER13).

Go to the Tomcat console and you'll see that while the Web app is closed, the timer task is still in its own way-the stage has been removed and the entertainer continues to perform:

We can add the Timer.cancel () code in contextdestroyed (Servletcontextevent arg0) by changing the code of the list Startcycleruntask, Stop the timer manually after the Web container is closed to end the task.

The Timerfactorybean and Schedulerfactorybean provided by spring for JDK timer and Quartz Scheduler can be associated with the life cycle of the spring container, starting the scheduler when the spring container is started, The scheduler is stopped when the spring container is closed. So in spring, with these two factorybean to configure the scheduler, and then get the Scheduler reference from the spring IOC for task scheduling, there will be no problem that the Web container shuts down and the task is still running. If you use a timer or scheduler directly in your program, you will see this problem if you do not perform additional processing.

Java Daemon Thread

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.