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 try1finally executed1inside try2finally executed2inside try3finally executed3inside try4finally executed4inside try5finally executed5inside try6finally executed6inside try7finally executed7inside try8finally executed8inside try9finally executed9inside try10main thread exited