Reputation: 6947
I have a situation in which I need to do some thread cleanup while the application is running. (This in turn is largely due to library design choices, which unfortunately are outside of my control.)
I do not have access to any relevant java.lang.Thread instance, because the thread is created outside of my code's control. This means that the simple approaches suggested at for example Java Thread Primitive Deprecation, How to Stop a Thread and How can I interrupt a thread created from within a method? don't really help me, because they all rely on the Thread instance either being available, or being possible to make available.
I do however have (brand new) code that calls ThreadMXBean.dumpAllThreads(), which returns ThreadInfo[]. This looked like a good starting point for cleaning up, since the returned array gives me all the information I need to determine which specific threads, if any, need to be cleaned up.
From what I understand, what I want to do is to call Thread.interrupt(). See for example How exactly do I interrupt a thread?. The problem with this is that I can't seem to find any way to do so given only a ThreadInfo object.
With the above said, I am ready to state the question:
How do I get from a ThreadInfo object to a corresponding Thread object, so that I can call methods on the Thread object instance?
Alternatively, what is some other method of effectively calling Thread.interrupt() on a thread given only a ThreadInfo object describing the thread?
Suggested solutions should ideally work with both Java 7 and Java 8. They need to work with Java 8.
Any recommendations?
Upvotes: 1
Views: 335
Reputation: 129
In ThreadInfo you have the thread id so you can use it to obtain a reference to a thread.
Read this question about how to do it.
I'd do something like this:
ThreadInfo[] threadInfos = ....;
Set<Long> tIds = new HashSet<>();
for (ThreadInfo tIndo : threadInfos) {
tIds.add(tIndo.getId());
}
for (Thread t : Thread.getAllStackTraces().keySet()) {
if(tIds.contains(t.getId()) {
t.interrupt();
}
}
Upvotes: 2