Java Reference
In-Depth Information
The figure shows three topics placed on a stack. Book-1 was placed first, Book-2 second, and Book-3 third.
Book - 3 , which is added last onto the stack, represents the top of the stack. Book-1 , which is added first onto the stack,
represents the bottom of the stack. Adding an element to a stack is called a push operation and removing an element
from a stack is called a pop operation. Initially, a stack is empty and the first operation is the push operation. When a
stack is being discarded, it must perform an equal number of push and pop operations so it is empty again.
Each thread in Java is allocated a stack to store its temporary data. A thread stores the state of a method
invocation onto its stack. The state of a Java method comprises the parameters' values, local variables, any
intermediate computed values, and the method's return value, if any. A Java stack consists of stack frames. Each frame
stores the state of one method invocation. A new frame is pushed onto a thread's stack for a method invocation. The
frame is popped from a thread's stack when the method completes.
Suppose a thread starts at the m1() method. The m1() method calls the m2() method, which in turn calls the m3()
method. Figure 9-5 shows the frames on the stack of a thread when methods m1() , m2() , and m3() are called. Note that
the figures shows the frames when the method m3() is called from the method m2() , which in turn is called from
the method m1() .
Top of stack
Top of stack
Top of stack
Top of stack
Frame of m3( )
Frame of m2( )
Frame for m2( )
Frame for m1( )
Frame of m1( )
Frame of m1( )
m2( ) invoked
m3( ) invoked
m1( ) invoked
Initial state
Top of stack
Top of stack
Top of stack
Frame for m2( )
Frame for m1( )
Frame for m1( )
m3( ) finished
m2( ) finished
m1( ) finished
Figure 9-5. State of the stack of a thread when methods m1(), m2(), and m3() are called
You can get some pieces of information about the stack of a thread at a specific point in time. Note that the state
of a thread's stack is always changing as the program executes. Therefore, you get a snapshot of the stack of a thread as
it existed at the time you requested it. An object of the java.lang.StackTraceElement class represents a stack frame.
You can query four pieces of information about a stack frame: class name, file name, method name, and line number.
To get the stack information, you need to call the getStackTrace() method of a Throwable object. It returns an array
of StackTraceElement objects. The first element of the array represents the top stack frame. The last element of the
array represents the bottom stack frame. When you create an object of the Throwable class (or any exception class in
Java), it captures the stack of the thread that is executing.
 
 
Search WWH ::




Custom Search