Search code examples
javamultithreadingconcurrencygraceful-degradation

How to degrade a program gracefully when there are waiting threads?


I know the construct of terminating a thread gracefully:

public class Foo implements Runnable {
   private volatile boolean stop = false;

   public void stop() {
      stop = true;
   }

   public void run() {
      while (!stop) {
         ...
      }
   }
}

But if some thread is waiting for something, inside some object (using wait(), without time limit), then this construct won't be useful to stopping this thread, because he is already past the condition in the while loop, so he will continue forever.

So, what is the right way to stop the waiting threads?


Solution

  • If the Thread is actually waiting for something, you should call the method Thread.interrupt() to interrupt the thread. Instead of checking for your custom variable in the while loop, use Thread.isInterrupted() or Thread.interrupted() - one resets the interruption flag, the other doesn't.

    If you are waiting on something, I assumed you had to catch the InterruptedException, didn't you?