Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a thread by Id

Tags:

java

jmx

I worked in JMX java and I get all the thread IDs by using the getAllThreadIds () method of the interface ThreadMXBean but I need a way to kill the thread of a given ID.

for example:

ThreadMXBean tbean;
tbean = ManagementFactory.getThreadMXBean();
long[] IDs=tbean.getAllThreadIds();
//.... I need a way to kill the Threads which have this IDs
like image 719
ofloflofl Avatar asked Aug 14 '13 06:08

ofloflofl


2 Answers

You can try this:

public void printAllThreadIds() {
    Thread currentThread = Thread.currentThread();
    ThreadGroup threadGroup = getRootThreadGroup(currentThread);
    int allActiveThreads = threadGroup.activeCount();
    Thread[] allThreads = new Thread[allActiveThreads];
    threadGroup.enumerate(allThreads);

    for (int i = 0; i < allThreads.length; i++) {
        Thread thread = allThreads[i];
        long id = thread.getId();
        System.out.println(id);
    }
}

private static ThreadGroup getRootThreadGroup(Thread thread) {
    ThreadGroup currentGroup = thread.getThreadGroup();

    ThreadGroup parentGroup;
    while ((parentGroup = currentGroup.getParent()) != null) {
        currentGroup = parentGroup;
    }

    return currentGroup;
}

But you should interrupt a Thread and not stop it.

The Thread.stop() method is deprecated, because it immediately kills a Thread. Thus data structures that are currently changed by this Thread might remain in a inconsistent state. The interrupt gives the Thread the chance to shutdown gracefully.

like image 152
René Link Avatar answered Sep 20 '22 15:09

René Link


There is actually no good way to kill a thread in java. There used be an api called Thread.stop() but it is also deperecated. Check this link for more details why Thread.stop was bad and how we should be stopping a thread.

http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

Getting just the thread id will not help you, you need to have the thread object reference to set a flag to stop that thread.

like image 44
Juned Ahsan Avatar answered Sep 19 '22 15:09

Juned Ahsan