Search code examples
javatomcatjvmjava-threads

Scenario's where a Java thread running in infinite loop for a long run be terminated by JVM


I have a Runnable thread which loops through an infinite loop. Per iteration it sleeps upto next task time and then does some task. This task is very critical hence makes the thread running it also very critical. I am not really a java thread expert so I was wondering what can be the various scenarios or possibilities where the JVM may decide to stop / terminate this thread. At the application level there is no restriction for number of running threads or so. I am concerned about how JVM would behave for a long-run.

For now everything works fine in my local test system but I could hardly test this for some hours. This is an web application running under Apache Tomcat.

The thread creation and running is simple as shown below :

Thread taskThread = new Thread(new TaskRunnable(taskObject));
taskThread.start();

Loop :

public void run()
{
  for (;;)
  {
    long sleepTime = this.taskObject.getNextTaskTime() - System.currentTimeMillis();

    if (sleepTime > 0L) {
      try
      {
        Thread.sleep(sleepTime);
      }
      catch (InterruptedException localInterruptedException)
      {
        localInterruptedException.printStackTrace();
      }
    }
    this.taskObject.performTask(); // also computes next task time
  }
}

Or this will work fine for a long-run as long as there are no exceptions in the running thread itself..


Solution

  • Java does not terminate threads on it's own unless one of three things happen:

    1. The JVM is shut down
    2. The thread's (or it's Runnable's) run() method exits
    3. An uncaught exception is thrown from it's (or it's Runnable's) run() method.

    This thread will stay up as long as the JVM is up or it is interrupted:

    public class MyLongRunningThread extends Thread {
        @Override
        public void run() {
            while(true) {
                try {
                    // Do stuff
                 } catch(InterruptedException e) {
                     // The thread was interrupted, which means someone wants us to stop
                     System.out.println("Interrupted; exiting");
                     return;
                 } catch(RuntimeException e) {
                     e.printStackTrace();
                 }
            }
        }
    }
    

    Note that the only way the thread will be interrupted is if you (or some framework you're using) calls it's interrupt() method.