since main()
runs on a thread. and as soon as the main()
finishes, main-thread should stop. So if main()
has invoked a long running th
To answer your question why, it's because making your thread a non-daemon thread means that you don't want it to be terminated abruptly, you want it to be terminated in an orderly way by running to completion or by being canceled. If your thread was killed by the JVM once main was exited that would be equivalent to making the thread a daemon.
The process will terminate when there are no more non-daemon threads, killing any daemon threads if necessary. However, if you do have any non-daemon threads, those will prevent the process from terminating.
From Thread.setDaemon:
Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads.
This method must be invoked before the thread is started.
And from section 12.8 of the JLS:
A program terminates all its activity and exits when one of two things happens:
All the threads that are not daemon threads terminate.
Some thread invokes the exit method of class Runtime or class System, and the exit operation is not forbidden by the security manager.
if your long running thread is not a daemon thread, it will not get terminated once the main thread exits. The JVM continues to run threads until the exit method of Runtime is called (and permitted to run) or all non-daemon threads have died. If your long running thread is not a daemon thread, JVM will not exit (i.e. thread will continue to be available for running).