Can you print out what line in the code and what method a running thread is in, from within a program - without using some monitoring software like visualvm? Do you have to extend Thread?
-
"how to view where a thread is in code.." Why to view where a thread is in code (with the arbitrary constraints)? What program feature does this support?Andrew Thompson– Andrew Thompson2012-08-04 01:54:54 +00:00Commented Aug 4, 2012 at 1:54
-
if a thread gets stuck in a network call and there are many different network calls, its helpful to know which oneMichael Roller– Michael Roller2012-08-04 02:04:45 +00:00Commented Aug 4, 2012 at 2:04
-
What are you trying to do? Is there a specific issue that you are trying to deal with, or is this just a more general question out of curiosity?John Kane– John Kane2012-08-04 06:11:56 +00:00Commented Aug 4, 2012 at 6:11
5 Answers
If this is just for quick-and-dirty debugging or error reporting, you can just do
new Exception().printStackTrace()
If you want to be a little fancier than that, you can use Thread.currentThread().getStackTrace() to get an array of StackTraceElement objects; you can determine the current line number by examining those.
Comments
Just use Thread.dumpStack(), which prints out the stack (similar to when an exception is uncaught). There's no need to create a new exception.
Comments
You can do this with a call to Thread.getStackTrace(). It returns an array of StackTraceElement, which represents the current StackTrace. It will be helpful to remember that the top couple elements are going to be methods in Thread, so the ones that you are likely interested in will be down the array a bit.
Of course you need to get a hold of the Thread that is currently running...
Thread.getCurrentThread().getStackTrace()
1 Comment
You could check out JDB. This link shows an example of using it to debug concurrency issues. This also just shows some of its basic functionality. Its pretty decent and I believe it should already be in your JAVA_HOME/bin.
Another alternative is to check out the JUCProfiler, I havn't tried this one, but it seems pretty decent.