Mes Mes - 2 months ago 12
Java Question

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

Answer

"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!

Comments