jdk/src/share/classes/java/lang/Thread.java
/**
* Returns an array of stack trace elements representing the stack dump
* of this thread. This method will return a zero-length array if
* this thread has not started, has started but has not yet been
* scheduled to run by the system, or has terminated.
* If the returned array is of non-zero length then the first element of
* the array represents the top of the stack, which is the most recent
* method invocation in the sequence. The last element of the array
* represents the bottom of the stack, which is the least recent method
* invocation in the sequence.
*
* <p>If there is a security manager, and this thread is not
* the current thread, then the security manager's
* <tt>checkPermission</tt> method is called with a
* <tt>RuntimePermission("getStackTrace")</tt> permission
* to see if it's ok to get the stack trace.
*
* <p>Some virtual machines may, under some circumstances, omit one
* or more stack frames from the stack trace. In the extreme case,
* a virtual machine that has no stack trace information concerning
* this thread is permitted to return a zero-length array from this
* method.
*
* @return an array of <tt>StackTraceElement</tt>,
* each represents one stack frame.
*
* @throws SecurityException
* if a security manager exists and its
* <tt>checkPermission</tt> method doesn't allow
* getting the stack trace of thread.
* @see SecurityManager#checkPermission
* @see RuntimePermission
* @see Throwable#getStackTrace
*
* @since 1.5
*/
public StackTraceElement[] getStackTrace() {
{- -------------------------------------------
(1) 処理対象がカレントスレッドであれば, 新しい Exception オブジェクトを作り,
そこから java.lang.Throwable.getStackTrace() メソッドでスタックトレースを取得すればいいだけ.
そうでなければ, (もし存在するなら SecurityManager によるチェックを行った後) 以下のように処理する.
* 処理対象がもう死んでいる場合 (= isAlive() が false の場合)
EMPTY_STACK_TRACE をリターンする
* 処理対象がまだ生きている場合 (= isAlive() が true の場合)
java.lang.Thread.dumpThreads() を呼んでスタックトレースを取得する.
(StackTraceElement の配列が返ってくるので, その先頭要素だけを使用)
結果が null でなければ, その結果をリターンする.
結果が null であれば EMPTY_STACK_TRACE をリターンする.
---------------------------------------- -}
if (this != Thread.currentThread()) {
// check for getStackTrace permission
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkPermission(
SecurityConstants.GET_STACK_TRACE_PERMISSION);
}
// optimization so we do not call into the vm for threads that
// have not yet started or have terminated
if (!isAlive()) {
return EMPTY_STACK_TRACE;
}
StackTraceElement[][] stackTraceArray = dumpThreads(new Thread[] {this});
StackTraceElement[] stackTrace = stackTraceArray[0];
// a thread that was alive during the previous isAlive call may have
// since terminated, therefore not having a stacktrace.
if (stackTrace == null) {
stackTrace = EMPTY_STACK_TRACE;
}
return stackTrace;
} else {
// Don't need JVM help for current thread
return (new Exception()).getStackTrace();
}
}
This document is available under the GNU GENERAL PUBLIC LICENSE Version 2.