Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I have to manually stop threads in Java?

When my application is ready to exit, either by closing a window or invoking the System.exit() method. Do I have to manually stop the threads I may have created or will Java take care of that for me?

like image 532
Dave Avatar asked Aug 21 '10 06:08

Dave


2 Answers

In cases you use System.exit(). All the threads will stop whether or not they are daemon.

Otherwise, the JVM will automatically stop all threads that are daemon threads set by Thread.setDaemon(true). In other words, the jvm will only exit when only threads remaining are all daemon threads or no threads at all.

Consider the example below, it will continue to run even after the main method returns. but if you set it to daemon, it will terminate when the main method (the main thread) terminates.

public class Test {

    public static void main(String[] arg) throws Throwable {
       Thread t = new Thread() {
          public void run()   {
             while(true)   {
                try  {
                   Thread.sleep(300);
                   System.out.println("Woken up after 300ms");
                }catch(Exception e) {}
             }
          }
       };

       // t.setDaemon(true); // will make this thread daemon
       t.start();
       System.exit(0); // this will stop all threads whether are not they are daemon
       System.out.println("main method returning...");
    }
}
like image 85
naikus Avatar answered Oct 25 '22 16:10

naikus


If you want stop threads before exit gracefully, Shutdown Hooks may be a choice.

looks like:

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() { 
    //Stop threads }
});

See: hook-design

like image 31
卢声远 Shengyuan Lu Avatar answered Oct 25 '22 16:10

卢声远 Shengyuan Lu