I’m going to work on Daemon thread in my new job, but I have no idea what it is. This post summarizes some of the key points from a stackoverflow post.
First, let’s look at daemon threads in Unix. Simply put, they are threads running in the background that answer requests for services. You can check more of it on Wikipedia.
There are two types of Java thread:
- Normal/User thread: Generally all threads created by programmer are user thread (unless you specify it to be daemon or the parent thread spawning the new thread is a daemon thread). The main thread is by default a non daemon thread.
- Daemon thread: it is similar (I don’t know if I can say that. Correct me if I’m wrong please). Daemon threads are like a service providers for other threads or objects running in the same process as the daemon thread (In other words, they may serve the user threads). They are typically used for background supporting tasks.
Points to Note about Java Daemon Threads:
- (needs verification) It has very low priority and only executes when no other threads of the same program is running
- When there are no more user threads (meaning that only daemon threads are running in a program), the JVM will ends the program and exit. This is reasonable. If there are no one to serve any more, why keep the servants? (This is my own thoughts)
- When the JVM halts, all daemon threads are abandoned. The “finally blocks“ are not executed and stacks are not unwound (not sure what this means).
- Daemon threads usually have an infinite loop in its run() method that waits for the service request or performs the tasks of the thread.
- We can set a thread to be daemon through the setDaemon() method but we can only do that before the start of the thread.
- We can check if a thread is a user thread or daemon thread using isDaemon() thread.
Examples of Java Daemon Threads:
- Garbage collection. It runs in the background, claiming resources from unwanted objects.
- A good Java code example from that post, reposted on gist
Things to check…
- Non-daemon threads (default) can even live longer than the main thread.