Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interrupt this runnable

I have read a lot of questions and answers in StackOverflow about interrupting Threads by throwing InterruptedException.

But most of the answers are using just a for loop and from time to time they check if the thread is interrupted with : Thread.currentThread().isInterrupted().

My code is like :

   public class UploadVideoRunnable implements Runnable {

       @Override 
       public void run() {
          isUploaded = new uploadMedia(title, uri);
        }
    }

How/Where should I add code to check if thread is interrupted?

Sorry if this is a noob question but I have searched google a lot and haven't found an answer.

Thanks

EDIT : updated code, uploadMedia is a class and not a method

like image 457
Mes Avatar asked Feb 02 '26 18:02

Mes


1 Answers

"Interrupting" requires "cooperation" here.

This means: you can only interrupt calls ... that do contain such kind of loop construct:

while (notDone) { doSomething(); Thread.sleep(); }

or something alike. This means: you will have to look into that method uploadMedia() and see if that allows for such changes. So, you would change that to:

while (notDone) { 
  if(interrupted) {
    notDone = false;
   } else {
   doSomething(); 
   Thread.sleep(); 
   }
}

Of course, the above being more like "pseudo-code"; you have to fill out the details.

Alternatively, you can have a look into ExecutorServices; as there are some means to forcefully stop those; see here

EDIT: that shouldn't change a thing. You see - you are calling a method there; the constructor of that class. And for sure, that constructor will be calling other methods; and one of those other methods is the one that is running for a longer period of time to do its uploading work.

Finally: please note that interrupted could be also something like

if (externalThingy.hasBeenCancelled()) {

Meaning: you might have to add another parameter to your class; something that the Uploader class can query in some way to figure if it should stop doing what it is currently doing!

like image 99
GhostCat Avatar answered Feb 04 '26 07:02

GhostCat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!