6

I am using a Java based file conversion tool which converts PDF to DOCX, but sometimes while conversion it stuck, if input file size is more then 1 MB and start utilizing 100% CPU and more memory and keep running. I want to stop this continuous thread.

  1. I know stop() function is deprecated.
  2. Calling thread.interrupt(); is not helping, since thread is keep running.
  3. There is no loop in the code ...so cannot check for interrupted flag in loop

How to Stop a running Thread t.

public class ThreadDemo implements Runnable {

    Thread t;

    PdfToDocConversion objPdfToDocConversion;

    ThreadDemo() throws InterruptedException {

        t = new Thread(this);
        System.out.println("Executing " + t.getName());
        // this will call run() fucntion
        t.start();

        Thread.sleep(2000);

        // interrupt the threads
        if (!t.interrupted()) {
            System.out.println("Interrupted");

            t.interrupt();

        }

        System.out.println(t.isInterrupted()); // true 

        System.out.println(t.getName());

        System.out.println(t.isAlive());   /// still true 

        // block until other threads finish
        try {
            t.join();
        } catch (InterruptedException e) {
        }
    }

    public void run() {

        objPdfToDocConversion = new PdfToDocConversion();
        try {


    objPdfToDocConversion.convertDocToPdf();//inside this function thread got stuck

        } catch (InterruptedException e) {

            Thread.currentThread().interrupt(); 
            System.out.print(t.getName() + " interrupted:");
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        try {
            new ThreadDemo();
        } catch (InterruptedException e) {
                e.printStackTrace();
        }
    }
}
shirish sahu
  • 59
  • 1
  • 1
  • 6
  • I am not an expert, but I think you should never try to stop the thread. Instead let it finish by itself – Nabin Sep 25 '16 at 06:13
  • Possible duplicate of [How do you kill a thread in Java?](http://stackoverflow.com/questions/671049/how-do-you-kill-a-thread-in-java) – Aleksandr Erokhin Sep 25 '16 at 08:22

3 Answers3

4

You can build your own logic in killing the thread by the help of boolean flag.

public class RunningThread implements Thread {

   private volatile boolean running = true;

   public void run() {

     while (running) {
        try {
            // Add your code here
        } catch (InterruptedException e) {
             if(!running){
                break;
             }
        }
     }
   }

   public void stopThread() {
       running = false;
       interrupt();
   }

}

Here is the usecase:

RunningThread thread = new RunningThread();
thread.start(); // start the thread
thread.stopThread(); // stops the thread

The approach above is originally used by Google developers in on of there framework a.k.a Volley library.

Enzokie
  • 7,365
  • 6
  • 33
  • 39
  • Does interrupt throw an InterruptedException? – Amer Qarabsa Sep 25 '16 at 07:25
  • 1
    It does not throw `InterruptedException`, the main use of interrupt is to call another boolean flag in that thread; to be clear `if (Thread.interrupted()) {throw new InterruptedException();}` a good example of this is `sleep(n)`. The interrupt is a kind of special trigger for that flag. – Enzokie Sep 25 '16 at 07:43
  • Can you edit your answer regarding and thank you for the clarification – Amer Qarabsa Sep 25 '16 at 07:44
  • 1
    There is no loop in the code ...so cannot check for interrupted flag – shirish sahu Sep 25 '16 at 22:31
  • @Enzokie If you would have put if (Thread.interrupted()) { // Add your code here }with in your try block then the example would be more clear and more informative. In your current code interrupt() is ineffective as it can stop nothing. – supernova Jan 10 '18 at 08:24
  • @supernova yes you are right but that time making this answer I only consider the OP's situation, in his code he has `PdfToDocConversion#convertDocToPdf()` which throws `InterruptedException` so I am guessing that the `convertDocToPdf()` has a built in `if (Thread.interrupted())` behind the hood though the OP did not add the exact code of this method so I also stop refactoring my answer at that point, it is also the reason why I have `try-catch` in my code. – Enzokie Jan 10 '18 at 09:27
3

Thread.interrupt() only sets a flag within the Thread object that the Thread should be interrupted. It does not cause the target Thread to throw an InterruptedException, instead code that can be interrupted must continually check that flag to see if someone has requested it be interrupted. That code then must handle it, usually by throwing an InterruptedException.

Smith_61
  • 2,078
  • 12
  • 12
1

Some of the answers say about stopping the loop with volatile boolean isRunning but I do not see any loop in your example. Interrupting the thread does not actually interrupt it "right now". It just says "thread will be interrupted as soon as there will be such an opportunity". In your case I would suggest to close your PDF file and flag it with some boolean - then you can catch the IOException and if the flag is set - it means that you caused this situation and you can finish the thread.

Wojtek
  • 1,288
  • 11
  • 16
  • Actually there is no such is thing as interrupt "right now". It takes some cycles. – Enzokie Sep 25 '16 at 07:48
  • Thanks Wojciech Kazior , yes there is no loop in the code ...so cannot check for interrupted flag ..but thread is never getting interrupted ...and at last this thread is keep utilizing CPU and memory .and halt the application – shirish sahu Sep 25 '16 at 22:48
  • @shirishsahu Try to close your file connection and catch the IOException. Accept my answer if it helps, cheers! – Wojtek Sep 26 '16 at 14:46