Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Java Call Stack of a running application

I am working on very huge java web based application. As there is no proper logging done while development so its very difficult for me to put break point and debug the app as i dont know execution order. Is there any mechanism to get complete Call Stack of the the running java application after I perform some actions.

I searched it on net for long time but cannot came to concrete solution. Please suggest me if something is there for it. Thanks

like image 369
naeemgik Avatar asked Feb 05 '13 10:02

naeemgik


People also ask

How can I get the current stack trace in Java?

We can obtain a stack trace from a thread by calling the getStackTrace() method on the Thread instance. It returns an array of StackTraceElement, from which details about stack frames of the thread can be found.

Does Java have a call stack?

The call stack of the running Java program is modelled by three interfaces: Frame, which encapsulates the data stored in a single stack frame, such as the operand stack and local variables; FrameSource, which encapsulates the allocation and layout of Frames, controlling such things as the argument-passing mechanism; ...


2 Answers

Method 1: Use jstack utility from command line (part of the JDK distro).

Method 2: Send signal 3 to the java process, it will dump stack traces on stdout.

Method 3: Call Thread.getAllStackTraces () from within application:

public class StackTraceDumper
{
    public static dumpAllStackTraces ()
    {
        for (Map.Entry <Thread, StackTraceElement []> entry: 
            Thread.getAllStackTraces().entrySet ())
        {
            System.out.println (entry.getKey ().getName () + ":");
            for (StackTraceElement element: entry.getValue ())
                System.out.println ("\t" + element);
        }
    }
}

Then use StackTraceDumper.dumpAllStackTraces() where you need to dump stack traces.

like image 58
Mikhail Vladimirov Avatar answered Oct 16 '22 06:10

Mikhail Vladimirov


Thread.dumpStack() Prints a stack trace of the current thread to the standard error stream. Thread.getAllStackTraces() Returns a map of stack traces for all live threads. Thread.getStackTrace() Returns an array of stack trace elements representing the stack dump of this thread.

like image 21
Dewfy Avatar answered Oct 16 '22 04:10

Dewfy