Example usage for java.lang Thread getStackTrace

List of usage examples for java.lang Thread getStackTrace

Introduction

In this page you can find the example usage for java.lang Thread getStackTrace.

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

Returns an array of stack trace elements representing the stack dump of this thread.

Usage

From source file:org.jasig.portal.portlet.rendering.worker.PortletExecutionWorker.java

@Override
public V get(long timeout) throws Exception {
    if (this.future == null) {
        throw new IllegalStateException("submit() must be called before get(long) can be called");
    }//from  w w w .  ja v  a2  s .c  om

    this.retrieved = true;

    try {
        final long startTime = this.waitForStart(timeout);
        final long waitTime = Math.max(0, timeout - (System.currentTimeMillis() - startTime));
        return this.future.get(waitTime, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        this.logger.warn("Execution interrupted on portlet window " + this.portletWindowId, e);
        throw e;
    } catch (ExecutionException e) {
        this.logger.warn("Execution failed on portlet window " + this.portletWindowId, e);
        throw e;
    } catch (TimeoutException e) {
        final StringBuilder errorBuilder = new StringBuilder("Execution timed out on portlet window ");
        errorBuilder.append(this.portletWindowId);

        final Thread localWorkerThread = workerThread;
        if (localWorkerThread != null) {
            final State state = localWorkerThread.getState();
            final StackTraceElement[] stackTrace = localWorkerThread.getStackTrace();

            errorBuilder.append("\n\tPortlet Thread State: ").append(state).append("\n");
            errorBuilder.append("\tPortlet Thread Stack Trace: \n");

            for (final StackTraceElement stackTraceElement : stackTrace) {
                errorBuilder.append("\t\tat ").append(stackTraceElement).append("\n");
            }

            errorBuilder.append("Portal Stack Trace:");
        }

        this.logger.warn(errorBuilder, e);

        throw e;
    }
}

From source file:org.lareferencia.xoai.Context.java

/**
 * Restore the previous Authorisation System State. If the state was not
 * changed by the current caller a warning will be displayed in log. Use:
 * <code>/* w  w  w  . j a v  a  2 s  .c  om*/
 *     mycontext.turnOffAuthorisationSystem();
 *     some java code that require no authorisation check
 *     mycontext.restoreAuthSystemState(); 
 * </code> If Context debug is enabled, the correct sequence calling will be
 * checked and a warning will be displayed if not.
 */
public void restoreAuthSystemState() {
    Boolean previousState;
    try {
        previousState = authStateChangeHistory.pop();
    } catch (EmptyStackException ex) {
        //            log.warn(LogManager.getHeader(this, "restore_auth_sys_state",
        //                    "not previous state info available "
        //                            + ex.getLocalizedMessage()));
        previousState = Boolean.FALSE;
    }
    if (log.isDebugEnabled()) {
        Thread currThread = Thread.currentThread();
        StackTraceElement[] stackTrace = currThread.getStackTrace();
        String caller = stackTrace[stackTrace.length - 1].getClassName();

        String previousCaller = (String) authStateClassCallHistory.pop();

        // if previousCaller is not the current caller *only* log a warning
        if (!previousCaller.equals(caller)) {
            //                log
            //                        .warn(LogManager
            //                                .getHeader(
            //                                        this,
            //                                        "restore_auth_sys_state",
            //                                        "Class: "
            //                                                + caller
            //                                                + " call restore but previous state change made by "
            //                                                + previousCaller));
        }
    }
    ignoreAuth = previousState.booleanValue();
}

From source file:com.iorga.webappwatcher.analyzer.model.session.RequestsTimesAndStacks.java

private void computeGroupedStacksForRequest(final RequestEventLog request,
        final TreeNode<StackStatElement> groupedStacksRoot) {
    // retrieve all system logs for that request if any
    final List<SystemEventLog> systems = slowRequestSystemLogs.get(request);
    // for all that system events, will retrieve the thread of the request
    for (final SystemEventLog system : systems) {
        for (final Thread thread : system.getBlockedOrRunningThreads()) {
            if (thread.getId() == request.getThreadId()) {
                // This is the thread of the request, let's add the stack to the StackStatElement children
                final StackTraceElement[] stackTraces = thread.getStackTrace();
                recurseAddStackElement(groupedStacksRoot, stackTraces, stackTraces.length);
                break; // found
            }//from w  w w . j  av a 2s. co  m
        }
    }
}

From source file:com.dianping.dpsf.jmx.DpsfResponsorMonitor.java

private String getThreadStackTraces(RequestProcessor requestProcessor, State state, int threadCount) {
    ThreadGroup threadGroup = requestProcessor.getThreadPool().getFactory().getGroup();
    Thread[] threads = new Thread[threadGroup.activeCount()];
    threadGroup.enumerate(threads, false);
    StringBuilder builder = new StringBuilder();
    int count = 0;
    if (threads != null && threads.length > 0 && threadCount > 0) {
        for (Thread thread : threads) {
            if (state == thread.getState()) {
                count++;//w  ww .  j  a  v a 2s . c o m
                if (count > 1) {
                    builder.append("\r\n\r\n");
                }
                builder.append("Thread ").append(thread.getId()).append("  ").append(thread.getName())
                        .append(" (state = ").append(state).append(")").append("\r\n");
                StackTraceElement[] stackTrace = thread.getStackTrace();
                for (StackTraceElement ste : stackTrace) {
                    builder.append(ste.getClassName()).append("-").append(ste.getMethodName()).append("(")
                            .append(ste.getLineNumber()).append(")").append("\r\n");
                }
                if (count >= threadCount) {
                    break;
                }
            }
        }
    }
    return builder.toString();
}

From source file:org.apache.stratos.common.concurrent.locks.ReadWriteLock.java

/**
 * acquires read lock// w  w w.  j  a  va2 s. co m
 */
public void acquireReadLock() {
    Thread currentThread = Thread.currentThread();
    if (log.isDebugEnabled()) {
        log.debug(String.format("Acquiring read lock: [lock-name] %s [thread-id] %d [thread-name] %s",
                getName(), currentThread.getId(), currentThread.getName()));
    }

    lock.readLock().lock();

    if (readWriteLockMonitorEnabled) {
        Map<LockType, LockMetadata> lockTypeLongMap = getLockTypeLongMap(currentThread.getId());
        LockMetadata lockMetadata = new LockMetadata(getName(), LockType.Read, currentThread.getId(),
                currentThread.getName(), currentThread.getStackTrace(), System.currentTimeMillis());
        lockTypeLongMap.put(lockMetadata.getLockType(), lockMetadata);
    }

    if (log.isDebugEnabled()) {
        log.debug(String.format("Read lock acquired: [lock-name] %s [thread-id] %d [thread-name] %s", getName(),
                currentThread.getId(), currentThread.getName()));
    }
}

From source file:org.dspace.core.Context.java

/**
 * Turn Off the Authorisation System for this context and store this change
 * in a history for future use.//ww  w. j  a v  a 2  s .  c  o  m
 */
public void turnOffAuthorisationSystem() {
    authStateChangeHistory.push(ignoreAuth);
    if (log.isDebugEnabled()) {
        Thread currThread = Thread.currentThread();
        StackTraceElement[] stackTrace = currThread.getStackTrace();
        String caller = stackTrace[stackTrace.length - 1].getClassName();

        authStateClassCallHistory.push(caller);
    }
    ignoreAuth = true;
}

From source file:org.sakaiproject.status.StatusServlet.java

protected void reportThreadStackTraces(HttpServletResponse response) throws Exception {
    PrintWriter pw = response.getWriter();

    for (Thread thread : findAllThreads()) {
        if (thread != null) {
            String stackTrace = "";
            try {
                StackTraceElement[] stack = thread.getStackTrace();
                for (StackTraceElement ste : stack) {
                    stackTrace += ste.getClassName() + "." + ste.getMethodName() + "();" + ste.getFileName()
                            + ":" + ste.getLineNumber() + " ";
                }/* ww w.j a  va2s . c  o m*/
            } catch (Exception e) {
                stackTrace += "-";
            }
            pw.print(thread.getThreadGroup().getName() + " " + thread.getId() + " " + stackTrace + "\n");
        }
    }
}

From source file:org.dspace.core.Context.java

/**
 * Restore the previous Authorisation System State. If the state was not
 * changed by the current caller a warning will be displayed in log. Use:
 * <code>/*from   ww  w  .j ava2s.  c  o m*/
 *     mycontext.turnOffAuthorisationSystem();
 *     some java code that require no authorisation check
 *     mycontext.restoreAuthSystemState(); 
 * </code> If Context debug is enabled, the correct sequence calling will be
 * checked and a warning will be displayed if not.
 */
public void restoreAuthSystemState() {
    Boolean previousState;
    try {
        previousState = authStateChangeHistory.pop();
    } catch (EmptyStackException ex) {
        log.warn(LogManager.getHeader(this, "restore_auth_sys_state",
                "not previous state info available " + ex.getLocalizedMessage()));
        previousState = Boolean.FALSE;
    }
    if (log.isDebugEnabled()) {
        Thread currThread = Thread.currentThread();
        StackTraceElement[] stackTrace = currThread.getStackTrace();
        String caller = stackTrace[stackTrace.length - 1].getClassName();

        String previousCaller = (String) authStateClassCallHistory.pop();

        // if previousCaller is not the current caller *only* log a warning
        if (!previousCaller.equals(caller)) {
            log.warn(LogManager.getHeader(this, "restore_auth_sys_state",
                    "Class: " + caller + " call restore but previous state change made by " + previousCaller));
        }
    }
    ignoreAuth = previousState.booleanValue();
}

From source file:org.sakaiproject.status.StatusServlet.java

protected void reportThreadDetails(HttpServletResponse response) throws Exception {
    PrintWriter pw = response.getWriter();

    for (Thread thread : findAllThreads()) {
        if (thread != null) {
            String threadLocation = "";
            try {
                StackTraceElement ste = thread.getStackTrace()[0];
                StackTraceElement ste2 = thread.getStackTrace()[1];
                threadLocation = ste.getClassName() + "." + ste.getMethodName() + "()," + ste.getFileName()
                        + ":" + ste.getLineNumber() + "," + ste2.getClassName() + "." + ste2.getMethodName()
                        + "()," + ste2.getFileName() + ":" + ste2.getLineNumber();
            } catch (Exception e) {
                threadLocation = "?,?,?,?";
            }/*from   www . j  a v a  2  s .c om*/
            pw.print(thread.getThreadGroup().getName() + "," + thread.getId() + "," + thread.getName() + ","
                    + thread.getPriority() + "," + thread.getState().name() + ","
                    + (thread.isAlive() ? "" : "notalive") + "," + (thread.isDaemon() ? "daemon" : "") + ","
                    + (thread.isInterrupted() ? "interrupted" : "") + "," + threadLocation + "\n");
        }
    }
}

From source file:org.apache.stratos.common.concurrent.locks.ReadWriteLock.java

/**
 * acquires write lock//from www  .j av a  2 s . com
 */
public void acquireWriteLock() {
    Thread currentThread = Thread.currentThread();
    if (log.isDebugEnabled()) {
        log.debug(String.format("Acquiring write lock: [lock-name] %s [thread-id] %d [thread-name] %s",
                getName(), currentThread.getId(), currentThread.getName()));
    }

    if (readWriteLockMonitorEnabled) {
        // Check whether the thread has already taken a read lock before requesting a write lock
        Map<LockType, LockMetadata> lockTypeLongMap = getLockTypeLongMap(currentThread.getId());
        if (lockTypeLongMap.containsKey(LockType.Read)) {
            String message = String.format(
                    "System error, cannot acquire a write lock while having a "
                            + "read lock on the same thread: [lock-name] %s [thread-id] %d [thread-name] %s",
                    getName(), currentThread.getId(), currentThread.getName());
            InvalidLockRequestedException exception = new InvalidLockRequestedException(message);
            log.error(exception);
            throw exception;
        }
    }

    lock.writeLock().lock();

    if (readWriteLockMonitorEnabled) {
        LockMetadata lockMetadata = new LockMetadata(getName(), LockType.Write, currentThread.getId(),
                currentThread.getName(), currentThread.getStackTrace(), System.currentTimeMillis());
        Map<LockType, LockMetadata> lockTypeLongMap = getLockTypeLongMap(currentThread.getId());
        lockTypeLongMap.put(lockMetadata.getLockType(), lockMetadata);
    }

    if (log.isDebugEnabled()) {
        log.debug(String.format("Write lock acquired: [lock-name] %s [thread-id] %d [thread-name] %s",
                getName(), currentThread.getId(), currentThread.getName()));
    }
}