0

Imagine you have an application A and a Thread-class like:

public class MyThread extends Thread {...}

From A, you start the thread with:

new MyThread.start();

Then when application A finishes, does MyThread also stop? Otherwise, how to ensure that it will be interrupted?

Rolintocour
  • 2,934
  • 4
  • 32
  • 63
  • You could try `System.exit()` to stop the JVM entirely. Otherwise it will run as long as there is a live thread. Alternatively you could join your main thread on all the subthreads but since you're asking I assume that might be a little too complex for now. – Thomas Oct 30 '18 at 14:09
  • You can System.exit() to terminate the whole process. Because thread is created in saperate stack. Even garbage collector is not going to clean it. Or you need to set it as deamon thread. – Sudhir Ojha Oct 30 '18 at 14:11
  • What do you mean by "application A finishes"? –  Oct 30 '18 at 14:14
  • If thread is not infinitely running thread then thread will stop – Mahesh Oct 30 '18 at 14:19
  • My application A is a dropwizard application, it listen to rest calls. But it also needs to consume a queue to do some other calculation. Then when I stop my dropwizard server, the thread should also die. – Rolintocour Oct 30 '18 at 14:19
  • For how to write a task that responds to interruption see https://stackoverflow.com/a/5915306/217324. when the application exits you need to implement a callback that interrupts the thread, see https://stackoverflow.com/a/35996422/217324 (don't know if this applies to dropwizard or not). It's better to submit tasks to a threadpool than to fire up your own threads. – Nathan Hughes Oct 30 '18 at 15:45

2 Answers2

3

There are two ways that a thread can run in Java:

  • As a normal application Thread
  • As a "daemon" thread.

When the JVM exits, it checks to see if there are any non-daemon threads still running, and it will wait for those to exit. If you don't want the JVM to wait for those background threads, make sure to call the method setDaemon(true) on the Thread.

For more details, look at this other question:

What is a daemon thread in Java?

Also, as a side comment, the recommended way to run a thread in Java these days is to implement Runnable, not extend Thread. See more details here.

"implements Runnable" vs "extends Thread" in Java

mjuarez
  • 16,372
  • 11
  • 56
  • 73
0

By default, no, the JVM will continue running until your thread exits. You can use System.exit to stop the JVM entirely from any thread, or Thread.setDaemon(true) to mark your thread as a daemon which means it will not stop the JVM from exiting.

apetranzilla
  • 5,331
  • 27
  • 34