Summary of daemon threads in Java

Source: Internet
Author: User

There are two types of threads in Java: User thread and daemon thread)

For example, Any daemon thread is a nanny of all non-daemon threads in the JVM:

As long as there is still any non-daemon thread in the current JVM instance that is not finished, the daemon thread will all work. Only when the last non-daemon thread ends, the daemon thread will end working with the JVM.
Daemon is used to facilitate the running of other threads. The most typical application of daemon is GC (Garbage Collector), which is a very competent guardian.

There is almost no difference between user and daemon. The only difference lies in the departure of virtual machines. If all user threads have exited and only the daemon thread exists, the virtual machine will quit. Because daemon has no protection, there is no work to do, and there is no need to continue running the program.


It is worth mentioning that the daemon thread is not provided only within the virtual machine. You can also set the daemon thread when writing a program. The following method is used to set the daemon thread.

Thread daemontread = new thread (); // set daemonthread as the daemonthread and default false (non-daemonthread) as the daemonthread. setdaemon (true); // verify whether the current thread is a daemonthread. If true is returned, the daemonthread is used. isdaemon ();

Note the following points:

(1) thread. setdaemon (true) must be set before thread. Start (); otherwise, an illegalthreadstateexception occurs. 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 consider that all applications can be allocated to daemon for service, such as read/write operations or computing logic.

Because it is impossible for you to know whether daemon has completed the expected service task before all the users are completed. Once the user exits, a large amount of data may not be read or written, and the computing task may run differently for multiple times. This is devastating to the program. The reason for this result has already been said: once all user threads leave, the virtual machine will quit.

// Complete the daemon task of file output import Java. io. *; Class testrunnable implements runnable {public void run () {try {thread. sleep (1000); // After the daemon.txt thread is blocked for 1 second, run file F = new file ("daemon.txt"); fileoutputstream OS = new fileoutputstream (F, true); OS. write ("daemon ". getbytes ();} catch (ioexception E1) {e1.printstacktrace ();} catch (interruptedexception E2) {e2.printstacktrace () ;}} public class testdemo2 {public static void main (St Ring [] ARGs) throws interruptedexception {runnable TR = new testrunnable (); thread = new thread (TR); thread. setdaemon (true); // sets the daemon thread. start (); // start executing the sub-process} // running result: the daemon.txt file does not contain the "daemon" string.

As you can see, it is terrible to package the input and output logic into the daemon thread. the string is not written to the specified file. The reason is also very simple. The daemon thread is still blocked for 1 second until the main thread is completed. At this time, the main thread will soon run out, the virtual machine will quit, and daemon will stop the service, and the output operation will naturally fail.

Public class test {public static void main (string ARGs) {thread T1 = new mycommon (); thread t2 = new thread (New mydaemon (); t2.setdaemon (true ); // set it to the daemon thread t2.start (); t1.start () ;}} class mycommon extends thread {public void run () {for (INT I = 0; I <5; I ++) {system. out. println ("thread 1" + I + "times! "); Try {thread. Sleep (7);} catch (interruptedexception e) {e. printstacktrace ();}}}}

Class mydaemon implements runnable {public void run () {for (long I = 0; I <9999999l; I ++) {system. out. println ("background Thread No." + I + "times! "); Try {thread. Sleep (7);} catch (interruptedexception e) {e. printstacktrace ();}}}}

The background thread executes 0th times!
Thread 1 executes 0th times!
Thread 1 executes 1st times!
The background thread executes 1st times!
The background thread executes 2nd times!
Thread 1 executes 2nd times!
Thread 1 executes 3rd Times!
The background thread executes 3rd Times!
Thread 1 executes 4th times!
The background thread executes 4th times!
The background thread executes 5th times!
The background thread executes 6th times!
The background thread executes 7th times!
Process finished with exit code 0
The preceding execution results show that:
The foreground thread ensures that the execution is complete, and the background thread exits after the execution is complete.

In fact, the standard for jre to determine whether the program is executed is that all the frontend thread lines are completed, regardless of the background thread status. Therefore, you must pay attention to this issue when using the background county seat.

Note:
Definition: daemon thread, also known as "service thread", automatically leaves when no user thread is available for service.
Priority: the daemon thread has a low priority and is used to provide services for other objects and threads in the system.
Set: Use setdaemon (true) to set the thread to "daemon" and set a user thread
The daemon method is to use the setdaemon method of the thread object before the thread object is created.
Example: The garbage collection thread is a classic daemon thread.
Thread, the program will no longer produce garbage, the garbage collector will have nothing to do, so when the garbage collection thread is
When there are only threads left on the JVM, the garbage collection thread automatically leaves. It is always running in a low-level state, used
Resources in the real-time monitoring and management system can be recycled.
Life cycle: daemon is a special process running in the background. It is independent of the control terminal and
Periodically execute a task or wait for some events to be processed. That is
It is said that the daemon thread does not depend on the terminal, but on the system, and is "Same as the system ". The Java daemon thread is
What does it look like. When all the threads in the JVM are daemon threads, the JVM can exit. If there is another
Or the above non-daemon threads will not exit the JVM.

Example:

In the persistent-connection comet server push technology, the message push thread is set as a daemon thread, serving the servlet user thread of chatservlet. After the servlet init starts, the message thread exits automatically after the servlet is destroyed.

The container receives a Servlet request. The scheduling thread selects a worker thread from the thread pool and passes the request to the worker thread. Then, the thread executes the servlet service method. When this thread is being executed, the container receives another request. The scheduling thread also selects another worker thread from the thread pool to serve new requests, 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 Service () method of the servlet will be concurrently executed in multiple threads.
By default, the servlet container uses a single instance multi-thread method to process requests. This reduces the cost of the servlet instance and increases the response time to the request. For tomcat. set the number of threads in the thread pool through the <connector> element in XML.

 

Why use a daemon thread?

We know that static variables are at the classloader level. If the web application stops, these static variables will also be cleared from the JVM. However, the thread is JVM-level. If you start a thread in a web application, the lifecycle of the thread will not be synchronized with the Web application. That is to say, even if you stop the web application, this thread is still active. It is precisely because of this obscure problem that many experienced developers do not agree to start threads in Web applications without permission.

If we manually use JDK timer (quartz schedmer), start timer when the Web container is started. When the Web container is closed, unless you manually close this timer, otherwise, tasks in the timer will continue to run!

The following is a small example to demonstrate this "weird" phenomenon. We use servletcontextlistener to create a timer at Web Container startup and periodically run a task:

// Code list startjavaseruntask: Container listener package COM. baobaotao. web; import Java. util. date; import Java. util. timer; import Java. util. timertask; import javax. servlet. servletcontextevent; import javax. servlet. servletcontextlistener; public class startjavaseruntask implements servletcontextlistener... {private timer; Public void contextdestroyed (servletcontextevent arg0 )... {// ② this method is executed when the Web container is closed. out. println ("disabling web application startup... ");} public void contextinitialized (servletcontextevent arg0 )... {// ② automatically execute this method system when the Web Container starts. out. println ("Web application startup... "); timer = new timer (); // ②-1: Create a timer. The timer automatically creates a background thread, timertask task = new simpletimertask (); timer. schedule (task, 1000l, 5000l); // ②-2: register a task that runs once every 5 seconds} class simpletimertask extends timertask... {// ③ task private int count; Public void run ()... {system. out. println (++ count) + "execute task... "+ (new date ()));}}

Declare the Web Container listener in Web. xml: <? XML version = "1.0" encoding = "UTF-8"?>
<Web-app>
...
<Listener>
<Listener-class> com. baobaotao. Web. startjavaseruntask </listener-class>
</Listener>
</Web-app>

After the web application is deployed and started in Tomcat, you can see that the task is executed every five seconds.
After running for a period of time, log on to the Tomcat management background and disable the corresponding web application (chapter13.

Go to the Tomcat console, and you will see that although the web application has been disabled, the timer task is still being executed in the same way-the stage has been removed and the play continues to perform:

You can add the timer. Cancel () code to contextdestroyed (servletcontextevent arg0) by changing the code of the starttriggeruntask list. After the Web container is closed, manually stop timer to end the task.

The timerfactorybean and schedulerfactorybean provided by spring for JDK timer and quartz scheduler can be associated with the lifecycle of the spring container. When the spring container is started, the scheduler is started. When the spring container is closed, stop the scheduler. Therefore, configuring the scheduler through the two factorybeans in spring and getting the scheduler reference from Spring IoC for task scheduling will not cause the problem that the Web container is closed and the task is still running. If you directly use timer or schedmer in the program, this problem will occur if no additional processing is performed.




Reprint please indicate the source http://blog.csdn.net/shimiso

Welcome to our technical exchange group: 173711587

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.