How do I get stacktrace of a particular line of Java program - java

How do we get the stacktrace for a successfully executed line in Java? It's needed to debug an issue.
I dont want a normal stacktrace, I want to know what a particular line is doing behind the scenes.
BeanFactory factory = new XmlBeanFactory(new FileSystemResource("/opt/data/ws_server.xml"));
serviceHelper = (ServiceHelper)factory.getBean("serviceHelper");
//Assuming no exceptions, print/view stack trace of above line (factory.getBean).
I want to see the stacktrace for factory.getBean - like below, to understand what factory.getBean is doing.
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:757)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:721)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:384)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:251)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:156)
- locked <0xffffffff58100608> (a java.util.concurrent.ConcurrentHashMap)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:248)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:160)

In the end, you are asking for some sort of instrumentation. In other words: you want to tell the jvm to keep track of the call stack and more importantly, make that information available to you programmatically.
And even when you only want that to happen for specific methods, the jvm still has to track all method invocations, as it can't know whether one of the methods to track is called in the end. Thus there is no way of tracking method invocations easily without performance impacts. And the tools I know that can keep that performance impact on a reasonable level, like XRebel are for later evaluation, not for programmatic consumption.
In other words: the only solutions to hang situations are:
doing a thread dump and analyzing it
doing extensive logging/tracing while your code is running, to analyze that in case or hangs
Just to be clear: what you are asking for, to get a stack trace of already executed code after the fact is impossible to achieve!

Please look in following answer.
Get current stack trace in Java
Basically it is Thread.currentThread().getStackTrace()

Related

How to view the current thread heap and variables?

I have a thread question.
consider the following simple method.
void do_something(){
//access the current thread heap memory content!?
}
And we would call it from different threads, the question is how would I access the called(current) thread heap memory?! just something like eclipse debug mode.
I know this is a weird question and there are much better solutions to accomplish this, but I just want to know.
I also could get the current stack by Thread.currentThread().getStackTrace(), but It's not really a real stack(at least for me) I just expected something like above, but I don't know how!
push str
call method0
pop str
push abc
push cvb
call method2
...
thanks in advance
Heap content is hard to get hold of since the heap implementation is JVM dependent. You can however get hold of such information via the Java Virtual Machine Tools Interface. This is what Eclipse and other debuggers do. Remember that you have to run you application in debugging mode in order to make use of this interface. You can find documentation on Java debugging on the pages of Oracle.
What you describe to be a stack comes closest to Java byte code. It is much easier to get hold of that. (Byte code represents a method implementation.) You can look at ASM which is a framework for reading Java classes. (Byte code operates on top of a stack but it is not one by itself.)
For your information: Java knows different kind of stack
A thread's method stack: Each thread has a stack of methods that were called for this thread were the current method is on top of the stack. If the top method calls another method, this called method is pushed on top of this stack and becomes the new current method.
Each such method has a call stack where values are pushed and poped from during method invocation. In order to add two numbers, for example, you need to push two numbers on this call stack and direct an addition by a specific byte code instruction.
Besides these two most commonly referred Java stacks, a Java virtual machine has several internal stacks such as the native method stack. This is very implementation specific and you normally do not want to mess with this memory area.
If you just want to analyze the normal path a method goes without actually tracing a running method invocation, have a look at ASM. Otherwise, you chose a quite difficult task.

Why do we have exit codes in Java?

In Java, we use System.exit(int) to exit the program.
The reason for an "exit value" in C was that the exit value was used to check for errors in a program. But in Java, errors are reflected by an Exception being thrown, thus they can be handled easily. So why do we have exit values in Java at all?
exit values are returned to the calling program e.g. the shell. An Exception cannot be caught by an external program.
BTW When you throw an Exception it is caught by that thread or that thread dies, the finally blocks are still called for that thread. When you call System.exit(), all threads stop immediately and finally blocks are not called.
For the same reason.
Exit codes are exclusively used by parties and applications outside of the program for debugging and handling purposes. A super-application can definitely handle a return code better than trying to parse a stack trace.
Also, if you are creating an application for an end-user, you would much rather exit gracefully from your app than post a bunch of stack trace information, for a couple of reasons: one, you will just be scaring them with lots of crazy-looking techno-gibberish, and two, stack traces often reveal sensitive and confidential information about the way the program is structured fundamentally (giving a potential attacker more knowledge about the system).
For a real-world example, I was working on a Java Batch program which used exit codes for its jobs. A user could see whether the job executed successfully or not based on whether the exit code was "0". If it was anything else, they could contact technical support, armed with the additional information of the exit code, and the help desk would have all the necessary information based on that exit code to help them out. It works much nicer than trying to ask a non-technical end-user, "Okay, so what Exception are you getting?"
exit values are returned to the callers to signal the successful or insuccessful completion of the program. The caller may not be able to catch the exception and handle it accordingly.
For eg. 0 exit value means successful completion whereas non-zero return value means some error in execution.
Also, System.exit() will make all the threads in the application to stop at that point itself.
Long story short, Exit codes are simplified signals to the user who encounters an exception while running a Java program. Since we assume that most of the users do not understand stack trace data of an exception, these simple non zero custom code will tell them that something is wrong and this should be reported to the vendor. So the vendor gets the code and he knows the stack trace associated with that code and tries to repair the system. This is an abstraction provided by the programmers so that users don't have to read and report voluminous stack traces. A very good analogy here is the getErrorCode() method in SQLException class. This method also closes the current JVM that is running on the client machine. This implies that this terminates all the threads that are in the JVM. This method calls the exit method in the class Java.lang.Runtime. If you go to the documentation of this method, you will understand how virtual machine is shut down.
This is the link
http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html#exit%28int%29

How do stack traces get generated?

No single method in a program "knows" where it is on the stack. All it knows is its own little job, and it does that and returns. So when an Exception is thrown and a stack trace is printed, where does this come from?
Is there implicitly a separate Thread running alongside of every application in the JVM that's monitoring the state of the program? Or does the JVM itself hold this information and the Exceptions somehow pull that data from it when they are thrown?
If either of these is the case, is it possible to use some call to retrieve a stack trace (either from the monitor Thread or the JVM) without throwing an Exception?
Every thread will have its own stack. Each method call creates a stack frame. If something wrong happened in code of any method, that will propagated to caller method. This way JVM can trace which method generated error and what is the call hierarchy.
If you observe the stack trace properly, you will see the method where error occured at top and the hierarchy in bottom.
There is a great lecture in youtube by a Stanford professor to understand how does it work. I would suggest watching it.
NOTE: This is theory. If you would like to know how API works, #Peter Lawrey answer may help you.
It comes from the Thread class that is running through the code.
Thread.dumpStack();
To see it you can just:
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
for (int i=0; i < trace.length; i++)
System.out.println("\tat " + trace[i]);
You can know the Thread a method belongs to by using Thread.currentThread. Using this thread, you can get the StackTrace, because there is a stack for every thread in the JVM. Also, the main program runs in the main thread.
When you create a Throwable (not when you throw it) it records the stack trace is a low level/hidden way associated with the Throwable. When you call getStackTrace() the first time it creates the StackTraceElement[] objects from the low level information. It doesn't this lazily as the stack trace is often not used.

In Java, it's possible discover what was the current method/methods executed?

I'm working with threads but after a time, most of them stop doing their job. The first thing I thought was a deadlock, but all are with state RUNNING.
I suppose there is an error in my logic or a new characteristic that I not realized and I must handle (it's a webcrawler).
Is it possible to get the current executing method or operation? I want this to see where my threads are trapped.
EDIT: I think that is something I need to handle or there is error in my logic because this happens after a time executing, not imeddiatly after the start.
A debugger is the way to go. This is what they are designed for.
Java debuggers with threading support are built into both the Eclipse and Netbeans IDEs.
Make VM to dump the threads (Ctrl-Break). Find your threads in the list. Look at the topmost stacktrace method. Done.
You can get the current stack trace in Java. You will get an array of StackTraceElement elements.
The first item in the array is the currently executing method.
See the following question for how to get the stack trace:
Get current stack trace in Java
Code might look like:
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
StackTraceElement yourMethod = trace[1];
System.out.println(yourMethod.getMethodName());
You have 2 options:
Use debug to get some understanding that was executed and what not.
Use a lot of logmessages (you can also produce stacktraces in that messages)
Thread dumps are the right solution for the problem. If you want to do it programmatically within the process (some kind of monitoring logic), then java.lang.management.ThreadMXBean provides access to all threads along with their current stacks at the time.
It is, throw an exception, catch it immediately and save the stack. This is about as performant as asking an elephant to fly overseas but it's possible since it sort of extracts the current call stack to something you can work with.
However, are you sure you haven't run into a livelock?
Do you suppose your web crawler program is in a loop processing the same urls. Add some high level logging so each thread writes what it's processing.

Monitoring Java from within Java

I want to write a simple visualization of a Java program by displaying the program's method calls as branches of a tree. This could be done quite simply by having the program itself tell the visualization what it is doing, but I want to be able to do this with any Java method/class and not just the ones I modify to do so.
What I need is the ability to watch the methods a program calls and what methods are called within that method and so on. Obviously, stack traces provide exactly this functionality:
java.lang.NullPointerException
at MyClass.mash(MyClass.java:9)
at MyClass.crunch(MyClass.java:6)
at MyClass.main(MyClass.java:3)
So I thought about having the program I want to monitor run in a thread and then just look at that thread's stack. However, the thread class does not really support this. It only supports printing the current stack.
Now I, of course, thought of simply changing the PrintStream of the System class so the thread would print its stack into my PrintStream, but this feels kind of wrong.
Is there a better way to do this? Are there any pre-existing classes/methods I can use?
Also, I'm currently downloading the Java source code, to check how exactly the thread class prints its stack so I could maybe subclass thread and imitate the dumpStack() method with my own getStack() method.
Look also at VisualVM, shipped with latest Java releases.
Oh shoot, looking through the source code I noticed the thread class has a method public StackTraceElement[] getStackTrace(), it just wasn't in the documentation I was reading. Now I feel dumb.
So yeah, that seems to be the solution.
One approach might be to use something like BCEL to preprocess the target bytecode to insert calls to your own code on every method entry and exit (probably best to do exit by wrapping the whole method in a try/finally block, to catch exception exits). From this, you can deduce the call tree exactly as it happens.
You could use AspectJ for that. Have a look at this description of exactly your use case.
Have a look at the ThreadMXBean class -- it my provide what you need. Essentially, you:
call ManagementFactory.getThreadMXBean() to get an instance of ThreadMXBean;
call getAllThreadIds() on the resulting ThreadMXBean to enumerate current threads;
call getThreadInfo() to get the top n stack trace elements from a given list of threads.

Categories