How does daemon thread survive after JVM exits? How does daemon thread survive after JVM exits? multithreading multithreading

How does daemon thread survive after JVM exits?


They don't survive. The JVM will exit when all the threads, except the daemon ones, have died.

When you start your application, the JVM will start a single, non-daemon thread to run your static main method.

Once the main method exits, this main thread will die, and if you spawned no other non-daemon thread, the JVM will exit.

If however you started another thread, the JVM will not exit, it will wait for all the non-daemon threads to die before exiting.

If that thread you spawned is doing something vital, this is absolutely the right thing to do, however often you have some threads that are not that vital, maybe they are listening to some external event that may or may not happen.

So, in theory, you should place some code somewhere to stop all the threads you spawned to allow the JVM to exit.

Since this is error prone, it's way easier to mark such non-vital threads as daemons. If they are marked as such, the JVM will not wait for them to die before exiting, the JVM will exit and kill those threads when the "main threads" (those not marked as daemon) have died.

To put it in code, it's something like this :

public class Spawner {  public static void main(String[] args) {    Thread t = new Thread(new Runnable() {      public void run() {        while (true) {          System.out.println("I'm still alive");        }      }    });    // Try uncommenting/commenting this line    // t.setDaemon(true);    t.start();    System.out.println("Main thread has finished");  }}

(I haven't tested this code, wrote it here directly, so it could contain stupid mistakes).

When running this code with the line commented, the thread is not deamon, so even if your main method has finished, you'll keep on having the console flooded until you stop it with CTRL+C. That is, the JVM will not exit.

If you uncomment the line, then the thread is a daemon, and soon after the main method has finished, the thread will be killed and the JVM will exit, without the need for CTRL+C.