Reputation: 13160
I have a thread running a Callable, I have another thread that will interrupt the first thread if it takes too long, but the trouble is the interrupt seems to cause more problems down the line. So is there a way my second thread could view the stack of the thread running the Callable without interrupting it and hence without interfering with it.
Upvotes: 1
Views: 91
Reputation: 655
Also make sure you are not calling it too frequently. There is a performance penality that comes with this - first of all - all Stack Information needs to be gathered from all Threads - then it allocates memory on your heap which can lead to higher memory usage overall and more GC overhead.
And - to comment on the accuracy of these stack traces. You will most likely only get the information based on the latest safepoints of each thread. There is a great article that explains what safepoints are: http://chriskirk.blogspot.com/2013/09/what-is-java-safepoint.html
Upvotes: 0
Reputation: 20520
Yes, you can use Thread.getAllStackTraces()
to retrieve all stack traces for all visible threads. This is a Map<Thread,StackTraceElement[]>
that you can query to get the stack trace for the thread you're interested in.
If you have a reference t
to the particular thread you're interested in, then
t.getStackTrace()
is all you need.
Just be aware that the documentation says
Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace.
In my experience, stack traces have been limited to 1024 elements maximum.
Upvotes: 4