Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one stop a thread without a stop() method?

I have question about the Java threads. Here is my scenario:

I have a thread calling a method that could take while. The thread keeps itself on that method until I get the result. If I send another request to that method in the same way, now there are two threads running (provided the first did not return the result yet). But I want to give the priority to the last thread and don't want to get the results from the previously started threads. So how could I get rid of earlier threads when I do not have a stop method?

like image 469
bandit Avatar asked Jul 13 '10 16:07

bandit


People also ask

How do I stop a thread manually?

Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java. This method stops the execution of a running thread and removes it from the waiting threads pool and garbage collected. A thread will also move to the dead state automatically when it reaches the end of its method.

What should I use instead of thread stop?

Infinitely running thread can be stopped using boolean variable. Infinitely running thread can be stopped using interrupt() method. But stop() is a deprecated method.

Why was the stop () method on thread deprecated?

Certain thread APIs were introduced to facilitate thread suspension, resumption, and termination but were later deprecated because of inherent design weaknesses. For example, the Thread. stop() method causes the thread to immediately throw a ThreadDeath exception, which usually stops the thread.

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.


2 Answers

The standard design pattern is to use a local variable in the thread that can be set to stop it:

public class MyThread extends Thread {
   private volatile boolean running = true;

   public void stop() {
      running = false;
   }

   public void run() {
      while (running) {
         // do your things
      }    
   }
}

This way you can greacefully terminate the thread, i.e. without throwing an InterruptedException.

like image 190
Janick Bernet Avatar answered Nov 15 '22 04:11

Janick Bernet


The best way really depends on what that method does. If it waits on something, chances are an interrupt will result in an InterruptedException which you handle and cleanly exit. If it's doing something busy, it won't:

class Scratchpad {
    public static void main(String[] a) {
        Thread t = new Thread(new Runnable() {
            public void run() {doWork();}
        });
        t.start();

        try {
            Thread.sleep(50);
        } catch (InterruptedException ie) {}

        t.interrupt();
    }

    private static void doWork() {
        for ( long i = 1; i != 0; i *=5 );
    }
}

In the case above, the only viable solution really is a flag variable to break out of the loop early on a cancel, ala @inflagranti.

Another option for event-driven architectures is the poison-pill: if your method is waiting on a blocking queue for a new item, then you can have a global constant item called the "poison-pill" that when consumed (dequeued) you kill the thread:

try {
   while(true) {
      SomeType next = queue.take();
      if ( next == POISON_PILL ) {
          return;
      }
      consume(next);
   }
} catch //...

EDIT:

It looks like what you really want is an executor service. When you submit a job to an executor service, you get back a Future which you can use to track results and cancel the job.

like image 20
Mark Peters Avatar answered Nov 15 '22 03:11

Mark Peters