4

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?

3
  • "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? Commented 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 one Commented 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? Commented Aug 4, 2012 at 6:11

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

2

Using just about any logging framework, most support Thread Group/Name, Class, Method, Filename and line number capabilities

Comments

1

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

the stackTraceElement will be at position [1] not [0].
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.