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 thread which is yet to finish even after main()
has done all the task. Since main()
is returned, would the other threads be terminated? i guess no. but why?
public static void main(String[] s){
new LongRunningThread().start();
}
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With