904

Can anybody tell me what daemon threads are in Java?

Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
rocker
  • 11,317
  • 7
  • 22
  • 12
  • 24
    The `Thread` javadoc describes what they are: http://java.sun.com/javase/6/docs/api/java/lang/Thread.html – skaffman Feb 06 '10 at 14:54
  • 1
    http://www.answers.com/Q/What_is_a_daemon_thread – Robb Tsang Oct 11 '14 at 06:37
  • 3
    For Daemon Threads, when the JVM stops all daemon threads are exited Due to this reason daemon threads shouldn't be used often since cleanup might not be executed on them. For example any I/O would not gracefully exit and write/read all the way to the end. – msj121 Apr 17 '15 at 13:51

27 Answers27

704

A daemon thread is a thread that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection.

You can use the setDaemon(boolean) method to change the Thread daemon properties before the thread starts.

Gray
  • 115,027
  • 24
  • 293
  • 354
b_erb
  • 20,932
  • 8
  • 55
  • 64
  • 233
    For posterity, `setDamon(boolean)` can only be called before the thread has been started. By default the thread inherits the daemon status of its parent thread. – Gray Nov 30 '11 at 13:47
  • 2
    "does not prevent the JVM from exiting when the program finishes but the thread is still running" while @sateesh says that "JVM halts any remaining daemon threads are abandoned". So do daemon threads finish running when JVM exits? – Gerald Oct 16 '15 at 03:09
  • 36
    @Gerald, *ALL* threads are killed when the JVM exits. B_erb said, "...when the program finishes." What that means is, if the program does not explicitly kill the JVM, then the JVM will automatically kill itself when the last _non_-daemon thread ends. Normal threads define "when the program exits." Daemon threads don't. – Solomon Slow Dec 18 '15 at 00:23
  • 9
    So this line `thread that does not prevent the JVM from exiting when the program finishes but the thread is still running` basically means the JVM process that started the thread doesn't care if the daemon thread finished executing or not, it will just end itself if all the normal threads have finished execution. – Bhargav Apr 21 '17 at 12:00
  • @Gray so u cannot convert a user thread to daemon thread after the thread is started, but it can be converted to daemon thread before the user thread is started? if so why? –  May 23 '17 at 17:19
  • Because that's how the code works @HarishAmarnath. The javadocs on setDaemon() read "This method must be invoked before the thread is started.". – Gray May 23 '17 at 18:54
  • setDamon(boolean) if called after starting the thread, execution will fail with IllegalThreadStateException. – ChandraBhan Singh Jun 30 '18 at 10:48
  • 1
    @SolomonSlow What are the consequences of killing a daemon thread (for example, a garbage collector) while it is still doing its job, when the JVM ends? Thanks. – Venkat Ramakrishnan Sep 16 '18 at 06:32
  • @VenkatRamakrishnan, If terminating the JVM process while some thread still is running could have bad consequences, then that thread should not be a daemon. You mentioned the garbage collector. The garbage collector can be a daemon, because it has no side effect outside of the process. (I.e., it doesn't touch any files on disk, it doesn't talk to any network services, etc.) – Solomon Slow Sep 17 '18 at 01:49
371

A few more points (Reference: Java Concurrency in Practice)

  • When a new thread is created it inherits the daemon status of its parent.
  • When all non-daemon threads finish, the JVM halts, and any remaining daemon threads are abandoned:

    • finally blocks are not executed,
    • stacks are not unwound - the JVM just exits.

    Due to this reason daemon threads should be used sparingly, and it is dangerous to use them for tasks that might perform any sort of I/O.

The Guy with The Hat
  • 10,836
  • 8
  • 57
  • 75
sateesh
  • 27,947
  • 7
  • 36
  • 45
  • 5
    Why shouldn't daemon threads be used for I/O? Is it a concern about BufferedWriters etc not being flushed? – Paul Cager Jul 26 '13 at 10:04
  • 4
    @PaulCager Yeah, they can just get cut off at the knees in the middle of a write/read as well. – Cruncher Sep 11 '13 at 17:33
  • Would it be safe to use them to write to a transactional database? It seems that even if the thread died your DB would be left in a reasonable state (Assuming it wasn't writing anything you absolutely needed such as a current state that is updated every few minutes) – Bill K Feb 28 '14 at 19:08
  • @BillK You may still run into hanging connection issues if they're left in a Daemon thread. Most IO is not entirely atomic, there's often some type of cleanup to ensure that you don't leak resources, either at the JVM level, or on a remote location (like a DB with a connection left open) – C0M37 May 14 '14 at 02:31
  • 56
    The second point is nonsense. When the JVM halts, *all* threads die and no `finally` blocks are executed, regardless of whether the threads are daemon or not. So don’t call `System.exit(…)` if you think there might be running threads doing I/O. The only difference is that the JVM will trigger its own termination when only daemon threads are left. – Holger Jun 02 '14 at 10:41
  • 1
    I think daemon threads remain in memory as long as they are providing services to the user thread. – Malwinder Singh May 20 '15 at 11:04
  • 14
    What is meant by "stacks are not unwound"? – user2009750 May 21 '15 at 12:32
  • 1
    @ɢʜʘʂʈʀɛɔʘɴ I'm pretty sure the "stacks are not unwound" bullet point is there to underline that every method on the call stack of that thread is abandoned somewhere in the middle of its execution. – Theodore Murdock Jul 22 '15 at 17:09
  • 3
    @ɢʜʘʂʈʀɛɔʘɴ there are some explanations out there on "unwinding stacks," including this one: http://flylib.com/books/en/2.254.1.277/1/ – user766353 Aug 18 '15 at 20:18
  • 1
    So it's just another way to say "finally blocks are not executed", which makes it redundant. – user253751 Nov 18 '19 at 12:50
199

All the above answers are good. Here's a simple little code snippet, to illustrate the difference. Try it with each of the values of true and false in setDaemon.

public class DaemonTest {
    
    public static void main(String[] args) {
        new WorkerThread().start();

        try {
            Thread.sleep(7500);
        } catch (InterruptedException e) {
            // handle here exception
        }

        System.out.println("Main Thread ending") ;
    }

}

class WorkerThread extends Thread {
    
    public WorkerThread() {
        // When false, (i.e. when it's a non daemon thread),
        // the WorkerThread continues to run.
        // When true, (i.e. when it's a daemon thread),
        // the WorkerThread terminates when the main 
        // thread or/and user defined thread(non daemon) terminates.
        setDaemon(true); 
    }
    
    public void run() {
        int count = 0;

        while (true) {
            System.out.println("Hello from Worker "+count++);

            try {
                sleep(5000);
            } catch (InterruptedException e) {
                // handle exception here
            }
        }
    }
}
Sathvik
  • 565
  • 1
  • 7
  • 17
russ
  • 1,991
  • 1
  • 11
  • 2
  • 2
    @russ Good code snippet! I had to define WorkerThread class as static though. – xli Oct 31 '13 at 20:13
  • @xli you could have done new DaemonTest().new WorkerThread().start() too :) – abhy Jul 21 '16 at 06:17
  • @russ good example. I was aware of that the default one is "setDeamon(false)" if you do not explicitly define "setDaemon(true)" – huseyin Jul 23 '17 at 11:20
  • Having something like println() also in the `catch (InterruptException)` block would make it clear daemon threads aren't exiting via the interrupt mechanism and they're abruptly ceasing to exist. – antak Oct 07 '21 at 09:22
105

Traditionally daemon processes in UNIX were those that were constantly running in background, much like services in Windows.

A daemon thread in Java is one that doesn't prevent the JVM from exiting. Specifically the JVM will exit when only daemon threads remain. You create one by calling the setDaemon() method on Thread.

Have a read of Daemon threads.

aioobe
  • 413,195
  • 112
  • 811
  • 826
cletus
  • 616,129
  • 168
  • 910
  • 942
57

Daemon threads are like a service providers for other threads or objects running in the same process as the daemon thread. Daemon threads are used for background supporting tasks and are only needed while normal threads are executing. If normal threads are not running and remaining threads are daemon threads then the interpreter exits.

For example, the HotJava browser uses up to four daemon threads named "Image Fetcher" to fetch images from the file system or network for any thread that needs one.

Daemon threads are typically used to perform services for your application/applet (such as loading the "fiddley bits"). The core difference between user threads and daemon threads is that the JVM will only shut down a program when all user threads have terminated. Daemon threads are terminated by the JVM when there are no longer any user threads running, including the main thread of execution.

setDaemon(true/false) ? This method is used to specify that a thread is daemon thread.

public boolean isDaemon() ? This method is used to determine the thread is daemon thread or not.

Eg:

public class DaemonThread extends Thread {
    public void run() {
        System.out.println("Entering run method");

        try {
            System.out.println("In run Method: currentThread() is" + Thread.currentThread());

            while (true) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException x) {}

                System.out.println("In run method: woke up again");
            }
        } finally {
            System.out.println("Leaving run Method");
        }
    }
    public static void main(String[] args) {
        System.out.println("Entering main Method");

        DaemonThread t = new DaemonThread();
        t.setDaemon(true);
        t.start();

        try {
            Thread.sleep(3000);
        } catch (InterruptedException x) {}

        System.out.println("Leaving main method");
    }

}

OutPut:

C:\java\thread>javac DaemonThread.java

C:\java\thread>java DaemonThread
Entering main Method
Entering run method
In run Method: currentThread() isThread[Thread-0,5,main]
In run method: woke up again
In run method: woke up again
In run method: woke up again
In run method: woke up again
In run method: woke up again
In run method: woke up again
Leaving main method

C:\j2se6\thread>
Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126
Okky
  • 10,338
  • 15
  • 75
  • 122
45

daemon: d(isk) a(nd) e(xecution) mon(itor) or from de(vice) mon(itor)

Definition of Daemon (Computing):

A background process that handles requests for services such as print spooling and file transfers, and is dormant when not required.

—— Source: English by Oxford Dictionaries

What is Daemon thread in Java?

  • Daemon threads can shut down any time in between their flow, Non-Daemon i.e. user thread executes completely.
  • Daemon threads are threads that run intermittently in the background as long as other non-daemon threads are running.
  • When all of the non-daemon threads complete, daemon threads terminates automatically.
  • Daemon threads are service providers for user threads running in the same process.
  • The JVM does not care about daemon threads to complete when in Running state, not even finally block also let execute. JVM do give preference to non-daemon threads that is created by us.
  • Daemon threads acts as services in Windows.
  • The JVM stops the daemon threads when all user threads (in contrast to the daemon threads) are terminated. Hence daemon threads can be used to implement, for example, a monitoring functionality as the thread is stopped by the JVM as soon as all user threads have stopped.
Premraj
  • 72,055
  • 26
  • 237
  • 180
  • if you call System.exit(), no finally blocks are executed, regardless of the thread being a daemon thread. indeed finally blocks are executed in daemon threads even **after** the last user thread terminates if the JVM did not kill the thread yet – benez Mar 25 '16 at 19:55
  • 7
    A daemon thread executes at the same priority as its creating thread, unless it has been changed prior to starting. Daemon threads aren't necessarily 'service providers' or Windows services or anything else stated here: they are just threads that don't prevent the JVM from exiting. Period. – user207421 Mar 30 '17 at 23:08
38

A daemon thread is a thread that is considered doing some tasks in the background like handling requests or various chronjobs that can exist in an application.

When your program only have daemon threads remaining it will exit. That's because usually these threads work together with normal threads and provide background handling of events.

You can specify that a Thread is a daemon one by using setDaemon method, they usually don't exit, neither they are interrupted.. they just stop when application stops.

ArifMustafa
  • 4,617
  • 5
  • 40
  • 48
Jack
  • 131,802
  • 30
  • 241
  • 343
16

One misconception I would like to clarify:

  • Assume that if daemon thread (say B) is created within user thread (say A); then ending of this user thread/parent thread (A) will not end the daemon thread/child thread (B) it has created; provided user thread is the only one currently running.
  • So there is no parent-child relationship on thread ending. All daemon threads (irrespective of where it is created) will end once there is no single live user thread and that causes JVM to terminate.
  • Even this is true for both (parent/child) are daemon threads.
  • If a child thread created from a daemon thread then that is also a daemon thread. This won't need any explicit daemon thread flag setting. Similarly if a child thread created from a user thread then that is also a user thread, if you want to change it, then explicit daemon flag setting is needed before start of that child thread.
user207421
  • 305,947
  • 44
  • 307
  • 483
Kanagavelu Sugumar
  • 18,766
  • 20
  • 94
  • 101
  • This ins't quoted from anything. Don't use quote formatting for text that isn't quoted. First paragraph of the 'quotation' is incorrect, and contradicts the second. – user207421 Mar 30 '17 at 23:05
  • @EJP GOT IT, So every one has to give other people quotation here, not their own. OR ourselves has quote somewhere then point here ? – Kanagavelu Sugumar Mar 31 '17 at 07:02
  • Yes, *if* you quote someone you have to cite them, just like anywhere else, bit if you haven't quoted anybody don't format it as though you have. I can't make head or tail of your second sentence. – user207421 Oct 01 '19 at 10:31
14

Daemon Thread and User Threads. Generally all threads created by programmer are user thread (unless you specify it to be daemon or your parent thread is a daemon thread). User thread are generally meant to run our programm code. JVM doesn't terminates unless all the user thread terminate.

soubhagini
  • 141
  • 1
  • 2
12

Java has a special kind of thread called daemon thread.

  • Very low priority.
  • Only executes when no other thread of the same program is running.
  • JVM ends the program finishing these threads, when daemon threads are the only threads running in a program.

What are daemon threads used for?

Normally used as service providers for normal threads. Usually have an infinite loop that waits for the service request or performs the tasks of the thread. They can’t do important jobs. (Because we don't know when they are going to have CPU time and they can finish any time if there aren't any other threads running. )

A typical example of these kind of threads is the Java garbage collector.

There's more...

  • You only call the setDaemon() method before you call the start() method. Once the thread is running, you can’t modify its daemon status.
  • Use isDaemon() method to check if a thread is a daemon thread or a user thread.
coderatchet
  • 8,120
  • 17
  • 69
  • 125
zxholy
  • 401
  • 3
  • 9
  • 8
    -1, I don't believe that a daemon thread is inherently low-priority. Certainly no documentation I've seen states such. Also this SO answer claims that priority and daemon-ness are orthogonal: http://stackoverflow.com/a/10298353/839128 – MikeFHay Feb 09 '15 at 11:01
  • 5
    Daemon threads have nothing to do with priority. You can have a high priority daemon thread or a low priority non-daemon thread. – Gray Jan 15 '16 at 13:28
  • A daemon thread initially has the same priority as its creating thread. – user207421 Mar 30 '17 at 23:04
  • The statement "'Only executes when no other thread of the same program is running" is misleading. – Fredrick Gauss Nov 08 '19 at 07:16
11

In Java, Daemon Threads are one of the types of the thread which does not prevent Java Virtual Machine (JVM) from exiting. The main purpose of a daemon thread is to execute background task especially in case of some routine periodic task or work. With JVM exits, daemon thread also dies.

By setting a thread.setDaemon(true), a thread becomes a daemon thread. However, you can only set this value before the thread start.

Koray Tugay
  • 22,894
  • 45
  • 188
  • 319
Java Guru
  • 466
  • 4
  • 12
  • What are the other types of thread that do that? A: None. There are daemon threads and non-daemon threads, period. It is a binary, Two states. – user207421 Mar 30 '17 at 23:14
10

Daemon threads are like assistants. Non-Daemon threads are like front performers. Assistants help performers to complete a job. When the job is completed, no help is needed by performers to perform anymore. As no help is needed the assistants leave the place. So when the jobs of Non-Daemon threads is over, Daemon threads march away.

Harjit Singh
  • 905
  • 1
  • 8
  • 17
7

Here is an example to test behavior of daemon threads in case of jvm exit due to non existence of user threads.

Please note second last line in the output below, when main thread exited, daemon thread also died and did not print finally executed9 statement within finally block. This means that any i/o resources closed within finally block of a daemon thread will not be closed if JVM exits due to non existence of user threads.

public class DeamonTreadExample {

public static void main(String[] args) throws InterruptedException {

    Thread t = new Thread(() -> {
        int count = 0;
        while (true) {
            count++;
            try {
                System.out.println("inside try"+ count);
                Thread.currentThread().sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                System.out.println("finally executed"+ count);
            }
        }
    });
    t.setDaemon(true);
    t.start();

    Thread.currentThread().sleep(10000);
    System.out.println("main thread exited");
  }
}

Output

inside try1
finally executed1
inside try2
finally executed2
inside try3
finally executed3
inside try4
finally executed4
inside try5
finally executed5
inside try6
finally executed6
inside try7
finally executed7
inside try8
finally executed8
inside try9
finally executed9
inside try10
main thread exited
Bharat Sharma
  • 141
  • 1
  • 4
5

Daemon thread is just like a normal thread except that the JVM will only shut down when the other non daemon threads are not existing. Daemon threads are typically used to perform services for your application.

Chanikag
  • 1,419
  • 2
  • 18
  • 31
5

Daemon thread in Java are those thread which runs in background and mostly created by JVM for performing background task like Garbage collection and other house keeping tasks.

Points to Note :

  1. Any thread created by main thread, which runs main method in Java is by default non daemon because Thread inherits its daemon nature from the Thread which creates it i.e. parent Thread and since main thread is a non daemon thread, any other thread created from it will remain non-daemon until explicitly made daemon by calling setDaemon(true).

  2. Thread.setDaemon(true) makes a Thread daemon but it can only be called before starting Thread in Java. It will throw IllegalThreadStateException if corresponding Thread is already started and running.

Difference between Daemon and Non Daemon thread in Java :

1) JVM doesn't wait for any daemon thread to finish before existing.

2) Daemon Thread are treated differently than User Thread when JVM terminates, finally blocks are not called, Stacks are not unwounded and JVM just exits.

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
4

Daemon threads are as everybody explained, will not constrain JVM to exit, so basically its a happy thread for Application from exit point of view.

Want to add that daemon threads can be used when say I'm providing an API like pushing data to a 3rd party server / or JMS, I might need to aggregate data at the client JVM level and then send to JMS in a separate thread. I can make this thread as daemon thread, if this is not a mandatory data to be pushed to server. This kind of data is like log push / aggregation.

Regards, Manish

  • Here is a simple program showing daemon thread in java. http://www.journaldev.com/1072/java-daemon-thread-example – Pankaj Dec 31 '12 at 02:12
4

Daemon thread is like daemon process which is responsible for managing resources,a daemon thread is created by the Java VM to serve the user threads. example updating system for unix,unix is daemon process. child of daemon thread is always daemon thread,so by default daemon is false.you can check thread as daemon or user by using "isDaemon()" method. so daemon thread or daemon process are basically responsible for managing resources. for example when you starting jvm there is garbage collector running that is daemon thread whose priority is 1 that is lowest,which is managing memory. jvm is alive as long as user thread is alive,u can not kill daemon thread.jvm is responsible to kill daemon threads.

Bosco
  • 3,835
  • 6
  • 25
  • 33
user2663609
  • 407
  • 7
  • 10
3

Daemon threads are threads that run in the background as long as other non-daemon threads of the process are still running. Thus, when all of the non-daemon threads complete, the daemon threads are terminated. An example for the non-daemon thread is the thread running the Main. A thread is made daemon by calling the setDaemon() method before the thread is started

For More Reference : Daemon thread in Java

nyi
  • 3,123
  • 4
  • 22
  • 45
Sai Sunder
  • 1,001
  • 1
  • 11
  • 16
3

For me, daemon thread it's like house keeper for user threads. If all user threads finished , the daemon thread has no job and killed by JVM. I explained it in the YouTube video.

Gregory Nozik
  • 3,296
  • 3
  • 32
  • 47
3

Let's talk only in code with working examples. I like russ's answer above but to remove any doubt I had, I enhanced it a little bit. I ran it twice, once with the worker thread set to deamon true (deamon thread) and another time set it to false (user thread). It confirms that the deamon thread ends when the main thread terminates.

public class DeamonThreadTest {

public static void main(String[] args) {

    new WorkerThread(false).start();    //set it to true and false and run twice.

    try {
        Thread.sleep(7500);
    } catch (InterruptedException e) {
        // handle here exception
    }

    System.out.println("Main Thread ending");
    }
   }

   class WorkerThread extends Thread {

    boolean isDeamon;

    public WorkerThread(boolean isDeamon) {
        // When false, (i.e. when it's a user thread),
        // the Worker thread continues to run.
        // When true, (i.e. when it's a daemon thread),
        // the Worker thread terminates when the main
        // thread terminates.
        this.isDeamon = isDeamon;
        setDaemon(isDeamon);
    }

    public void run() {
        System.out.println("I am a " + (isDeamon ? "Deamon Thread" : "User Thread (none-deamon)"));

        int counter = 0;

        while (counter < 10) {
            counter++;
            System.out.println("\tworking from Worker thread " + counter++);

            try {
                sleep(5000);
            } catch (InterruptedException e) {
                // handle exception here
            }
        }
        System.out.println("\tWorker thread ends. ");
    }
}



result when setDeamon(true)
=====================================
I am a Deamon Thread
    working from Worker thread 0
    working from Worker thread 1
Main Thread ending

Process finished with exit code 0


result when setDeamon(false)
=====================================
I am a User Thread (none-deamon)
    working from Worker thread 0
    working from Worker thread 1
Main Thread ending
    working from Worker thread 2
    working from Worker thread 3
    working from Worker thread 4
    working from Worker thread 5
    working from Worker thread 6
    working from Worker thread 7
    working from Worker thread 8
    working from Worker thread 9
    Worker thread ends. 

Process finished with exit code 0
Tony
  • 1,458
  • 2
  • 11
  • 13
3

Daemon threads are generally known as "Service Provider" thread. These threads should not be used to execute program code but system code. These threads run parallel to your code but JVM can kill them anytime. When JVM finds no user threads, it stops it and all daemon threads terminate instantly. We can set non-daemon thread to daemon using :

setDaemon(true)
Pankti
  • 411
  • 4
  • 13
  • 3
    They are not 'generally known as "Service Provider" threads'. – user207421 Jan 07 '17 at 17:46
  • 1
    And they can be used to execute any code. The JVM cannot 'kill them any time', but it *will* kill them when there are no non-daemon threads running. – user207421 Mar 30 '17 at 23:12
  • @EJP maybe I am wrong but "it will kill them" when non-daemon threads running. When a thread is daemon, isn't it running separately holding the jvm until it executes completely and is now managed at OS level . – 89n3ur0n Jun 27 '17 at 11:57
  • It will kill them when all non-daemon threads have exited, and not a picosecond before. Certainly not 'any time'. – user207421 Oct 01 '19 at 10:34
3

There already are numerous answers; however, maybe I could shed a bit clearer light on this, as when I was reading about Daemon Threads, initially, I had a feeling, that I understood it well; however, after playing with it and debugged a bit, I observed a strange (to me) behaviour.

I was taught, that:

If I want the thread to die right after the main thread orderly finishes its execution, I should set it as Diamond.

What I tried:

  • I created two threads from the Main Thread, and I only set one of those as a diamond;
  • After orderly completing execution of the Main Thread, none of those newly created threads exited, but I expected, that Daemon thread should have been exited;
  • I surfed over many blogs and articles, and the best and clearest definition I found so far, comes from the Java Concurrency In Practice book, which very clearly states, that:

7.4.2 Daemon threads

Sometimes you want to create a thread that performs some helper function but you don’t want the existence of this thread to prevent the JVM from shutting down. This is what daemon threads are for. Threads are divided into two types: normal threads and daemon threads. When the JVM starts up, all the threads it creates (such as garbage collector and other housekeeping threads) are daemon threads, except the main thread. When a new thread is created, it inherits the daemon status of the thread that created it, so by default any threads created by the main thread are also normal threads. Normal threads and daemon threads differ only in what happens when they exit. When a thread exits, the JVM performs an inventory of running threads, and if the only threads that are left are daemon threads, it initiates an orderly shutdown. When the JVM halts, any remaining daemon threads are abandoned— finally blocks are not executed, stacks are not unwound—the JVM just exits. Daemon threads should be used sparingly—few processing activities can be safely abandoned at any time with no cleanup. In particular, it is dangerous to use daemon threads for tasks that might perform any sort of I/O. Daemon threads are best saved for “housekeeping” tasks, such as a background thread that periodically removes expired entries from an in-memory cache.

Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66
2

JVM will accomplish the work when a last non-daemon thread execution is completed. By default, JVM will create a thread as nondaemon but we can make Thread as a daemon with help of method setDaemon(true). A good example of Daemon thread is GC thread which will complete his work as soon as all nondaemon threads are completed.

Arman Tumanyan
  • 386
  • 3
  • 14
  • how can that be how the GC thread works? Doesn't garbage collection run even if the program's main thread takes a very long time (main thread doesn't terminate)? – Calicoder May 10 '18 at 22:06
  • As I mentioned GC thread will work till the end of last NON daemon thread will accomplish it’s execution. The program’s main thread is not daemon as we know hence GC thread will accomplish the work once main thread is completed/killed. Basically I want to say that daemon thread(s) will terminated when process is completed, and process is completed when all non daemon threads are executed. – Arman Tumanyan May 10 '18 at 22:10
  • By default the daemon status of a thread is inherited from its parent. – user207421 Oct 01 '19 at 10:37
2
  • Daemon threads are those threads which provide general services for user threads (Example : clean up services - garbage collector)
  • Daemon threads are running all the time until kill by the JVM
  • Daemon Threads are treated differently than User Thread when JVM terminates , finally blocks are not called JVM just exits
  • JVM doesn't terminates unless all the user threads terminate. JVM terminates if all user threads are dies
  • JVM doesn't wait for any daemon thread to finish before existing and finally blocks are not called
  • If all user threads dies JVM kills all the daemon threads before stops
  • When all user threads have terminated, daemon threads can also be terminated and the main program terminates
  • setDaemon() method must be called before the thread's start() method is invoked
  • Once a thread has started executing its daemon status cannot be changed
  • To determine if a thread is a daemon thread, use the accessor method isDaemon()
Malith Ileperuma
  • 926
  • 11
  • 27
1

Java daemon thread

[Daemon process]

Java uses user thread and daemon tread concepts.

JVM flow

1. If there are no `user treads` JVM starts terminating the program
2. JVM terminates all `daemon threads` automatically without waiting when they are done
3. JVM is shutdown

As you see daemon tread is a service thread for user treads.

  • daemon tread is low priority thread.
  • Thread inherits it's properties from parent thread. To set it externally you can use setDaemon() method before starting it or check it via isDaemon()
yoAlex5
  • 29,217
  • 8
  • 193
  • 205
0

Daemon Thread

Threads that run in the background are called daemon threads.

Example of Daemon Threads:

  1. Garbage Collector.
  2. Signal Dispatcher.

Objective of Daemon Thread:

The main objective of the daemon threads is to provide support to the non-daemon threads.

Additional information about Daemon Thread:

  1. Generally, Daemon threads run in the MIN_PRIORITY however, it is possible to run daemon threads with MAX_PRIORITY as well.

    Example: Usually the GC runs with a MIN_PRIORITY priority, however, once there is a requirement for additional memory. JVM increases the priority of the GC from MIN_PRIORITY to MAX_PRIORITY.



  1. Once the Thread has been started, it can't be changed from Daemon Thread to Non-Daemon Thread that will result in IllegalThreadStateException.

    Example:

    public static void main(String[] args) {
        Thread.currentThread().setDaemon(true);
    }
    

    Output:

    Exception in thread "main" java.lang.IllegalThreadStateException
        at java.base/java.lang.Thread.setDaemon(Thread.java:1403)
    


  1. If we are branching off a thread, the child thread inherits the nature of the parent thread. If the parent thread is a non-daemon thread automatically the child thread will be non-daemon as well and if the parent thread is a daemon, the child thread will be a daemon as well.

    class Scratch {
        public static void main(String[] args) {
            CustomThread customThread = new CustomThread();
            customThread.start();
        }
    }
    class CustomThread extends Thread{
        @Override
        public void run() {
            System.out.println(currentThread().isDaemon());
        }
    }
    

    Output:

     false
    


  1. When the last non-daemon thread terminates, all the daemon threads get terminated automatically.

    class Scratch {
        public static void main(String[] args) {
            System.out.println("Main Thread Started.");
    
            CustomThread customThread = new CustomThread();
            customThread.setDaemon(true);
            customThread.start();
    
            System.out.println("Main Thread Finished.");
        }
    }
    class CustomThread extends Thread{
        @Override
        public void run() {
            System.out.println("Custom Thread Started.");
            try {
                sleep(2000);
            } catch (InterruptedException ignore) {}
            System.out.println("Custom Thread Finished.");  //Won't get executed.
        }
    }
    

    Output:

    Main Thread Started.
    Main Thread Finished.
    Custom Thread Started.
    
Zahid Khan
  • 2,130
  • 2
  • 18
  • 31
0

User threads versus Daemon threads in java threads

  • Daemon Threads

this threads in Java are low-priority threads that runs in the background to perform tasks such as garbage collection. Daemon thread in Java is also a service provider thread that provides services to the user thread.

  • User Threads

this threads are high-priority threads. The JVM will wait for any user thread to complete its task before terminating it

"keep in mind both User and Daemon threads wrapped upon OS threads"

Recently OpenJdk proposed Virtual threads with in project Loom (which they are User based as well) you may find more on Fibers and Continuations for the Java Virtual Machine threads in here.

Lunatic
  • 1,519
  • 8
  • 24