Search code examples
javamultithreadinginterruption

How and Why Thread is interrupted under overloaded traffic


I have implemented a connection check thread. When I have created a heavy traffic I have realized that there are many "ConnWatchdogThread" instances. I think "continue" statement triggers the interrupted thread live and in that case new "ConnWatchdogThread" is created. If so how this happen? How thread is interrupted?

 private class ConnWatchdog extends Thread {

 public ConnWatchdog(){
 setName("ConnWatchdogThread");
 }
      private void checkConnections() {

   //connection check 
      }

      @Override
      public void run() {

         while (true) {
            try {
               Thread.sleep(checkPeriod);
            } catch (InterruptedException e) {
//              e.prinstackTrace()

               continue;
            }

            try {

               this.checkConnections();

            } catch (Throwable t) {

            }

         }

      }
   }

Solution

  • Interruption happens when the interrupt method on the thread is called. It's not shown in your example what is doing the interrupting. Here's an example of using interrupt.

    The continue advances control to the next iteration of the loop. So when something calls interrupt on your thread while it's sleeping, it bails out of the sleep (clearing the interrupt flag), then the continue sends it back to the top of the loop and it goes to sleep again, which seems pointless.

    Nothing in the code shown causes a new thread to be created.

    It would be more normal to use the interruption to exit the while loop and cause the thread to terminate. Using interruption for things other than thread-cancellation is not recommended (Java Concurrency in Practice, 7.1, page 138):

    There is nothing in the API or language specification that ties interruption to any specific cancellation semantics, but in practice, using interruption for anything but cancellation is fragile and difficult to sustain in larger applications.