Home > database >  Reset Variables After InterruptedException?
Reset Variables After InterruptedException?

Time:04-12

I have a program with multiple threads operating on a single instance of a class. Sometimes one of these threads will get interrupted. I have in the method header "throws InterruptedException" so it does that part correctly. The problem is that when a thread gets interrupted, the fields don't get reset, so the next thread that comes in gets all messed up.

How do I check if a thread is interrupted so that I can reset the variables for the next thread that comes in? I'm not sure where to address this in my code. I have tried something like:

if(Thread.currentThread().isInterrupted()) {
    //reset variables here
}

or:

if(Thread.interrupted()) {
    //reset variables here
}

Can anyone help me out? Thank you in advance!

CodePudding user response:

You can encase your whole thing in a try-catch block:

try {
    //Code here
} catch (InterruptedException e) {
    //Reset variables here
}

CodePudding user response:

You can check (or handle) if a thread has been interrupted in two ways:

  1. You receive an InterruptedException when performing operations that might keep your thread waiting for an undefined amount of time, like a sleep or a wait invocation.
public class MyRunnable implements Runnable {
   public void run(){
      try {
         while(true){
            someOperation();
            TimeUnit.SECONDS.sleep(2);
         }
      } catch(InterruptedException ex) {
         //reset variables
      }
   }
}
  1. If you're performing some heavy operations, you might wanna check in specific points of your code if you've received an interruption with the methods you mentioned above.
public class MyRunnable implements Runnable {
   public void run(){
      while(true){
         someHeavyOperation();
         if (Thread.currentThread().isInterrupted()){
            //reset variables
            return;
         }
      }
   }
}

Here's also a link to the Oracle Tutorials explaining Java's support to thread interruption

https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

  • Related