Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get stack trace of a thread

I have a multithreaded application. Several messages are coming to the application and are processed in separated threads. For this I am using classes ThreadPoolExecutor and FutureTask from package java.util.concurrent.

Occasionally I have some deadlocks in the application. When a deadlock occurs I want to interrupt the blocking thread and I want to log the stack trace of this thread so that I can later resolve the deadlock.

Is there any way how can we find the stack trace of a thread outside of that thread in Java?

like image 698
Palo Avatar asked Sep 17 '10 10:09

Palo


3 Answers

You could log the stack traces of all thread from time to time (or before killing the process) from within your application. To do that use:

Map<Thread, StackTraceElement[]> m = Thread.getAllStackTraces();
for(Map.Entry<Thread,  StackTraceElement[]> e : m.entrySet()) {
    log(e.getKey().toString());
    for (StackTraceElement s : e.getValue()) {
        log("  " + s);
    }
}

When running nightly automated tests, sometimes some one of the test cases gets into a deadlock. I added a "TimeBomb" daemon thread that waits 30 minutes, and if then logs all stack traces as above.

like image 60
Thomas Mueller Avatar answered Oct 20 '22 15:10

Thomas Mueller


See here for how to generate stack traces, including how to do this programatically. From the console, Ctrl+Break will dump the stack traces to stdout. See also this SO question for more details.

like image 21
Brian Agnew Avatar answered Oct 20 '22 16:10

Brian Agnew


Before entering the deadlock region, set a field like,

thread = Thread.currentThread();

In your monitoring thread you can perform thread.getStackTrace(); to get the stack trace of that thread at any time.

like image 36
Peter Lawrey Avatar answered Oct 20 '22 16:10

Peter Lawrey