0

I wrote a piece of Java code to test thread, like:

public static void main(String[] args) {

        Thread t = new Thread(() -> {
                throw new NullPointerException();
        });
        t.setDaemon(true);
        t.start();
    }

I expected to see something like :

Exception in thread "Thread-0" java.lang.NullPointerException
    at com.cisco.ruan.nio.Java8Time.lambda$0(Java8Time.java:23)
    at java.lang.Thread.run(Thread.java:745)

But nothing is printed out, unless I commented t.setDaemon(true);.

My question is why there is no message when there is a exception popped up in a daemon thread. What is the purpose of such design?

ruanhao
  • 4,663
  • 6
  • 28
  • 43

1 Answers1

4

It's because the JVM will exit before the exception is thrown, alternatively logged.

As quoted from https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#setDaemon(boolean)

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

Try doing a Thread.sleep(1000) right after t.start() to see if the message is logged.

jontro
  • 10,241
  • 6
  • 46
  • 71