How to Kill a Thread in Java

How do you kill a Thread in Java?

See this thread by Sun on why they deprecated Thread.stop(). It goes into detail about why this was a bad method and what should be done to safely stop threads in general.

The way they recommend is to use a shared variable as a flag which asks the background thread to stop. This variable can then be set by a different object requesting the thread terminate.

How to kill a running thread in wait?

When i try to kill my Robber threads, some die , but some get stuck in the wait() block , what would be a better way to kill all the threads ,

The right way to "kill" a thread is to interrupt it with thread.interrupt(). If the thread is blocked in a wait(...) call, this will immediately throw InterruptedException. When you catch InterruptedException it is a good idea to immediately re-interrupt the thread to preserve the interrupt flag because when the exception is thrown, the interrupt bit is cleared.

try {
...wait();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
// handle the interrupt
return;
}

Since not all methods throw InterruptedException, you can also check to make sure the thread has been interrupted with something like the following:

if (Thread.currentThread().isInterrupted()) {
// stop processing
return;
}

Or in your case something like:

while (alive && !Thread.currentThread().isInterrupted()) {

Btw, alive should be volatile because it looks to be accessed by multiple threads.

How to properly stop the Thread in Java?

In the IndexProcessor class you need a way of setting a flag which informs the thread that it will need to terminate, similar to the variable run that you have used just in the class scope.

When you wish to stop the thread, you set this flag and call join() on the thread and wait for it to finish.

Make sure that the flag is thread safe by using a volatile variable or by using getter and setter methods which are synchronised with the variable being used as the flag.

public class IndexProcessor implements Runnable {

private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
private volatile boolean running = true;

public void terminate() {
running = false;
}

@Override
public void run() {
while (running) {
try {
LOGGER.debug("Sleeping...");
Thread.sleep((long) 15000);

LOGGER.debug("Processing");
} catch (InterruptedException e) {
LOGGER.error("Exception", e);
running = false;
}
}

}
}

Then in SearchEngineContextListener:

public class SearchEngineContextListener implements ServletContextListener {

private static final Logger LOGGER = LoggerFactory.getLogger(SearchEngineContextListener.class);

private Thread thread = null;
private IndexProcessor runnable = null;

@Override
public void contextInitialized(ServletContextEvent event) {
runnable = new IndexProcessor();
thread = new Thread(runnable);
LOGGER.debug("Starting thread: " + thread);
thread.start();
LOGGER.debug("Background process successfully started.");
}

@Override
public void contextDestroyed(ServletContextEvent event) {
LOGGER.debug("Stopping thread: " + thread);
if (thread != null) {
runnable.terminate();
thread.join();
LOGGER.debug("Thread successfully stopped.");
}
}
}

How to kill a java thread?

Thread.interrupt() is the only safe method which is generally applicable. You can of course use other application-level signals (such as a conditional check on a volatile variable) to self-terminate. Other methods (such as all the deprecated Thread.xx methods) can pollute your application's state in non-deterministic ways, and would require reloading all application state.

How to interrupt or kill a java thread while it's running

The way you stop a thread is by asking it - nicely - to stop. It's up to the code the thread is running to listen for and act on that request.

Specifically, the way you do it is to interrupt the thread. Your code checks for the interruption - Thread.sleep and Object.wait will throw InterruptedException if the thread is interrupted before or during their execution; but you catch the interruption, and ignore it, so you won't act on it.

Instead of this:

while (condition) {
try {
Thread.sleep(...);

wait();
} catch (InterruptedException e) {
}
}

Put the interruption outside the loop:

try {
while (condition) {
Thread.sleep(...);
wait();
}
} catch (InterruptedException e) {
}

then the loop terminates if it is interrupted.



Related Topics



Leave a reply



Submit