Understanding and application of Java daemon threads

There are two types of threads in Java, namely User Thread (user thread) and Daemon Thread (daemon thread).
User threads are easy to understand. The business logic code we write in daily development runs in user threads. The daemon thread requires special understanding.

1.1 What is a daemon thread?

In the operating system, there is no concept of a daemon thread, only a daemon process. But the Java language mechanism is built on the basis of the JVM. This mechanism means that the Java platform shields the bottom layer of the operating system, so it can construct a mechanism that is beneficial to itself in its own virtual platform. . The designers of the Java language or platform were more or less influenced by the ideas of the Unix operating system, and the daemon thread mechanism was adapted to platforms such as the JVM, so daemon threads came into being.

The so-called daemon thread refers to a thread that provides a general service in the background when the program is running. For example, the garbage collection thread is a very competent guardian, and this thread is not an indispensable part of the program. Therefore, when all non-daemon threads end, the program terminates and all daemon threads in the process are killed. Conversely, as long as any non-daemon thread is still running, the program will not terminate.

In fact, there is essentially no difference between User Thread (user thread) and Daemon Thread (daemon thread). The only difference lies in the departure of the virtual machine: if all user threads have exited, only the daemon thread is left. The thread exists and the virtual machine exits. Because without the guardian, the daemon thread has no work to do, and there is no need to continue running the program.

1.2 Use and precautions of daemon threads

Daemon threads are not only provided inside the virtual machine. Users can also manually set/convert a user thread to a daemon thread.

The Thread class provides a setDaemon(true) method to set an ordinary thread (user thread) as a daemon thread.

public final void setDaemon(boolean on);

There are several points to note during use:
1.thread.setDaemon(true) must be set before thread.start(), otherwise an IllegalThreadStateException will be thrown. This also means that a running regular thread cannot be set as a daemon thread. This is obviously different from the daemon process in the operating system. After the daemon process is created, it allows the process to get rid of the control of the original session + let the process get rid of the control of the original process group + let the process get rid of the control of the original controlling terminal; so it is placed on The language mechanism of the virtual machine is essentially different from the system-level language.

2. The new thread generated in the Daemon thread also belongs to the Daemon. This point is fundamentally different from the daemon process in the operating system: the child process that comes out of the daemon process fork() is no longer a daemon process. Although it copies the process-related information of the parent process, the process of the child process The parent process is not the init process. The so-called daemon process essentially means that when the parent process dies, init will adopt the process, and then files 0, 1 and 2 are all /dev/null, and the current directory is /.

3. Not all applications can be assigned to Daemon threads for services, such as read and write operations or calculation logic. Because this kind of application may have exited the virtual machine before the Daemon Thread has time to operate. This also means that the daemon thread should never access inherent resources, such as files and databases, because it can be interrupted at any time, even in the middle of an operation.

The following is an example of a daemon thread task that completes file output:

import java.io.*;  

class TestRunnable implements Runnable {
    
    
    public void run(){
    
    
        try {
    
    
            Thread.sleep(1000); // 守护线程阻塞1秒后运行  
            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(String[] args) throws InterruptedException {
    
    
        Runnable tr = new TestRunnable();
        Thread thread = new Thread(tr);
        thread.setDaemon(true); // 设置守护线程(必须在thread.start()之前)
        thread.start(); // 开始执行分进程
    }
}

The result of running the above code is that there is no daemon string in the file daemon.txt.
But if you comment out the thread.setDaemon(true); line of code, the file daemon.txt can be written to the daemon string, because at this time the thread is an ordinary user thread.
A simple understanding is that the criterion for JRE to judge whether the execution of the program has ended is that all foreground threads (user threads) have completed execution, regardless of the status of the background threads (daemon threads).

1.3 Application scenarios of daemon threads

Having said so much before, what are the practical applications of Daemon Thread? For example, for a Servlet in a web server, when the container starts, a service thread, that is, a scheduling thread, will be initialized in the background, which is responsible for processing http requests. Then for each request, the scheduling thread will take out a worker thread from the thread pool. To handle the request to achieve the purpose of concurrency control. In other words, a scheduled thread is actually used in Java's thread pool.

1.4 Summary

From my understanding, the daemon thread is used to tell the JVM that my thread is a low-level thread, and there is no need to wait for it to finish running before exiting. The JVM can exit whenever it likes, regardless of this thread.
In daily business-related CRUD development, the concept of daemon threads is not actually paid attention to and is rarely used.
But if you want to go higher, you still need to understand these deep concepts, such as the underlying implementation of some frameworks.

Guess you like

Origin blog.csdn.net/liufang_imei/article/details/132712550