I have a multithreaded application and I assign a unique name to each thread through setName()
property. Now, I want functionality to get access to the threads
That's how I did it on the basis of this:
/*
MIGHT THROW NULL POINTER
*/
Thread getThreadByName(String name) {
// Get current Thread Group
ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
ThreadGroup parentThreadGroup;
while ((parentThreadGroup = threadGroup.getParent()) != null) {
threadGroup = parentThreadGroup;
}
// List all active Threads
final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
int nAllocated = threadMXBean.getThreadCount();
int n = 0;
Thread[] threads;
do {
nAllocated *= 2;
threads = new Thread[nAllocated];
n = threadGroup.enumerate(threads, true);
} while (n == nAllocated);
threads = Arrays.copyOf(threads, n);
// Get Thread by name
for (Thread thread : threads) {
System.out.println(thread.getName());
if (thread.getName().equals(name)) {
return thread;
}
}
return null;
}
An iteration of Pete's answer..
public Thread getThreadByName(String threadName) {
for (Thread t : Thread.getAllStackTraces().keySet()) {
if (t.getName().equals(threadName)) return t;
}
return null;
}
I like the HashMap idea best, but if you want to keep the Set, you can iterate over the Set, rather than going through the setup of converting to an array:
Iterator<Thread> i = threadSet.iterator();
while(i.hasNext()) {
Thread t = i.next();
if(t.getName().equals(threadName)) return t;
}
return null;
You can find all active threads using ThreadGroup:
ThreadGroup.getParent()
until you find a group with a null parent.ThreadGroup.enumerate()
to find all threads on the system.The value of doing this completely escapes me ... what will you possibly do with a named thread? Unless you're subclassing Thread
when you should be implementing Runnable
(which is sloppy programming to start with).