0

Here is my Thread:-

Thread t=new Thread(){
  public void run(){
      downloadFile();
  }
}
t.start();

public static void main(){
  t.interrupt();
}

Here downloadFile() is long running method (downloading file from server) The issue is , even though t.interrupt() is called downloadFile() method still keeps running which is not expected . I want downloadFile() method to terminate immediately as soon as the thread is interrupted. How should i achieve it ?

Thanks.

EDIT1:

Here is downloadFile() skeleton which calls the rest API to fetch file:

void downloadFile(){
  String url="https//:fileserver/getFile"
  //code to getFile method  
}

2 Answers2

0

Your Runnable needs to store an AtomicBoolean flag to say whether it has been interrupted or not.

The interrupt method should just set the flag to true.

The downloadFile() method needs to check the flag inside the download loop and abort the download if it is set.

Something like this is the only clean way to implement it as only downloadFile knows how to safely and cleanly interrupt itself, closing sockets etc.

Tim B
  • 40,716
  • 16
  • 83
  • 128
  • 1
    The problem is with the actual network operation. If there's a socket blocking on a read, the only surefire way to stop it is to close the socket. There's not necessarily any "download loop" (at least visible), unless he's writing raw network code himself. No need (or use) to duplicate the interrupt functionality either. – Kayaman Apr 18 '17 at 09:04
-1

You need some flag to inform a thread about termination:

public class FileDownloader implements Runnable {
    private volatile boolean running = true;

    public void terminate() {
        running = false;
    }

    @Override
    public void run() {
        while (running) {
            try {
                downloadFile();
            } catch (InterruptedException e) {
                running = false;
            }
        }

    }
}

in main:

FileDownloader fileDownloaderRunnable = new FileDownloader();
Thread thread = new Thread(fileDownloaderRunnable);
thread.start();
//terminating thread
fileDownloaderRunnable.terminate();
thread.join();
Bogdan Ustyak
  • 5,639
  • 2
  • 21
  • 16
  • Presumably the method `downloadFile()` downloads a single file fully. Your loop would therefore download the file over and over again until you stop it. That doesn't really make sense. – Kayaman Apr 18 '17 at 09:07