Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if main method completes the execution, what happens to any long running thread?

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();
}
like image 309
Ankit Avatar asked May 07 '13 18:05

Ankit


2 Answers

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.

like image 123
Jon Skeet Avatar answered Oct 02 '22 03:10

Jon Skeet


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).

like image 33
ali haider Avatar answered Oct 02 '22 03:10

ali haider