Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dump stacktraces of all active Threads

I'm trying to dump a list of all active threads including the current stack of each. I can get a list of all threads using threading.enumerate(), but i can't figure out a way to get to the stack from there.

Background: A Zope/Plone app freaks out from time to time, consuming 100% of cpu and needs to be restarted. I have a feeling it's a loop which doesn't terminate properly, but i cannot reproduce it in the test-environemt for verification. I managed to register a signal handler which can be triggered from the outside, so i can trigger some code as soon as the situation occurs again. If I could dump the stacktrace for all active threads, that would give me a clue what goes wrong. The hole thing runs on python 2.4...

Any ideas on how to trace down situations like these are appreciated :)

Cheers, Chriss

like image 850
Chriss Avatar asked Jun 23 '09 14:06

Chriss


People also ask

What are thread dumps?

A thread dump is a snapshot of the state of all threads that are part of the process. The state of each thread is presented with a so called stack trace, which shows the contents of a thread's stack. Some of the threads belong to the Java application you are running, while others are JVM internal threads.

How to dump Java thread stack?

To take a thread dump, navigate to the console used to launch the Java application, and press the CTRL and Break keys together. It's worth noting that, on some keyboards, the Break key isn't available. Therefore, in such cases, a thread dump can be captured using the CTRL, SHIFT, and Pause keys together.

How to check thread dump in Java?

Getting a Thread Dump Using jstack In JDK 1.6 and higher, it is possible to get a thread dump on MS Windows using jstack. Use PID via jps to check the PID of the currently running Java application process. Use the extracted PID as the parameter of jstack to obtain a thread dump.


1 Answers

As jitter points out in an earlier answer sys._current_frames() gives you what you need for v2.5+. For the lazy the following code snippet worked for me and may help you:

print >> sys.stderr, "\n*** STACKTRACE - START ***\n" code = [] for threadId, stack in sys._current_frames().items():     code.append("\n# ThreadID: %s" % threadId)     for filename, lineno, name, line in traceback.extract_stack(stack):         code.append('File: "%s", line %d, in %s' % (filename,                                                     lineno, name))         if line:             code.append("  %s" % (line.strip()))  for line in code:     print >> sys.stderr, line print >> sys.stderr, "\n*** STACKTRACE - END ***\n" 
like image 157
codeasone Avatar answered Sep 24 '22 17:09

codeasone