Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a thread nice in java?

A common question but I haven't found any acceptable answer.

I recently run in to the problem how to kill a thread in a nice way. I try to make a generic message handler that accepts runnables. The problem is that I can't exit the current runnable in a good way and fast enough.

The code in the runnables are unknown i.e. jni, pure java, 3:rd part lib etc. Below is a simple example with sleep that "steels" the interrupt so the thread never exits (fast enough): I wan't to be able to interrupt the thread at any time, only between each task are not acceptable. My first idea was to use thread.stop but that's deprecated.

Producer:

int i = 0;
MessageHandler handler = new MessageHandler();
handler.start();

handler.post(new Runnable() {
    @Override
    public void run() {
        System.out.println("task -" + i++ + " " + Thread.currentThread().getName());
        for (int r=0;r<1000000000;r++) {
            System.out.println("task -" + i++ + " " + Thread.currentThread().getName());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
});

try {
    Thread.sleep(500);
} catch (InterruptedException q) {
    q.printStackTrace();
}
handler.interrupt();

Consumer (MessageHandler):

package test;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MessageHandler extends Thread implements Runnable {

    private BlockingQueue<Runnable> msgQue = new LinkedBlockingQueue<Runnable>();
    private final static String TAG = "MessageHandler";

    public void run() {
        try {
            System.out.println(TAG + " Initialized "  + currentThread().getName());
            while(true) {
                Runnable task = msgQue.take();
                task.run();
                if (isInterrupted()) {
                    break;
                }
            }
        } catch (InterruptedException e) {
            System.out.println(TAG + " InterruptedException "  + currentThread().getName());
        } finally {
            System.out.println(TAG + " Exit "  + currentThread().getName());
            msgQue.clear();
            msgQue = null;
        }
    }

    public void post(Runnable task) {
        System.out.println(TAG + " post " + currentThread().getName());
        msgQue.add(task);
    }
}

I feel like a superman wihout any super power...

Hey, Oracle give my power back!

like image 274
volt Avatar asked Oct 15 '25 14:10

volt


1 Answers

Check out this faq on why they deprecated Thread.stop() and what to use instead. The gist of it is to use Thread.interrupt().

like image 68
nfechner Avatar answered Oct 17 '25 02:10

nfechner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!