Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a running Thread in Java

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();
        }
    }
}
like image 889
shirish sahu Avatar asked Sep 25 '16 06:09

shirish sahu


People also ask

Can we stop a running thread in Java?

Modern ways to suspend/stop a thread are by using a boolean flag and Thread. interrupt() method. Using a boolean flag: We can define a boolean variable which is used for stopping/killing threads say 'exit'. Whenever we want to stop a thread, the 'exit' variable will be set to true.

What is stop () method in Java?

stop() method is used to terminate the thread execution. Once thread executed is halted by stop() method, start() function cannot restart the thread execution. stop() function has been deprecated in the latest versions of java.

How do I stop a Java execution?

In Java exit() method is in java. This System. exit() method terminates the current JVM running on the system which results in termination of code being executed currently.


2 Answers

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.

like image 83
Enzokie Avatar answered Oct 21 '22 13:10

Enzokie


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.

like image 3
Smith_61 Avatar answered Oct 21 '22 12:10

Smith_61