Java daemon thread

Time:2022-1-22

1、 What is a daemon thread

Before talking about daemon threads, let’s talk about what user threads are.

User thread: the ordinary thread we usually create
Daemon thread: a service thread used to serve user threads; There is no need for upper logic intervention. Of course, we can also manually create a daemon thread. In the JVM, after all non daemon threads are executed, the virtual machine will automatically exit whether there is a daemon thread or not.

2、 Why do I need a daemon thread

When there is any user thread, the JVM will not exit. Under what circumstances can the JVM program exit normally?

The Java Virtual Machine exits when the only threads running are all daemon threads.

The above sentence comes from the official JDK document, which means:
When there is no running non daemon thread in the JVM, the JVM process exits.

First of all, understand,When any user thread exists, the JVM will not exit
Java daemon thread
Java daemon thread
If this user thread does not end, the JVM process cannot end. This leads to the question: who is responsible for ending this thread? So Java provides a daemon thread to help us solve this problem.

3、 How to use

It’s easy to use, just before calling the start () method,callsetDaemon(true)Mark the thread as a daemon
How to check whether a thread is a daemon thread or a user thread:useisDaemon()method
Java daemon thread
Java daemon thread
From the output of the console, we can see that when the main thread exits, the JVM will exit, and the daemon thread will be recycled at the same time. Even if you have an endless loop, it doesn’t matter.

be careful:

  • thread. Setdaemon (true) must be in thread Set before start(), otherwise it will be thrownIllegalThreadStateExceptionAbnormal.
  • The new thread generated in the daemon thread is also daemon’s.

4、 Role and application scenario of daemon thread

As we know above, if there is no running non daemon thread in the JVM, the JVM will exit at this time.

The garbage collection thread in the JVM is a typical daemon thread。 If this feature is not available, when the JVM wants to exit, the program cannot exit because the garbage collection thread is still running. It can be seen that the importance of guard threads.

Garbage collection is a mechanism that needs to be run all the time, but when there is no user thread, there is no need for garbage collection thread. The daemon thread just meets this demand.

Generally speaking, the daemon thread is often used to perform some background tasks. However, you want the thread to close automatically when the program exits, or when the JVM exits. At this time, the daemon thread is your first choice.