Java Stacktrace Print printStackTraces()

Here you can find the source of printStackTraces()

Description

Print a string representation of the current stack state of all the active threads.

License

Open Source License

Declaration

public static void printStackTraces() 

Method Source Code

//package com.java2s;
/*******************************************************************************
 *  Copyright (c) 2012 Google, Inc.//  ww w.  ja v  a2 s.c  o  m
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *  
 *  Contributors:
 *  Google, Inc. - initial API and implementation
 *******************************************************************************/

import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import java.util.Map;

import java.util.Map.Entry;

public class Main {
    /**
     * Print a string representation of the current stack state of all the active threads.
     */
    public static void printStackTraces() {
        printStackTraces(new PrintWriter(new OutputStreamWriter(System.err)));
    }

    /**
     * Print a string representation of the current stack state of all the active threads.
     */
    public static void printStackTraces(PrintWriter writer) {
        Map<Thread, StackTraceElement[]> map;
        try {
            map = Thread.getAllStackTraces();
        } catch (Throwable e) {
            writer.println("Failed to obtain stack traces: " + e);
            return;
        }
        if (map == null) {
            writer.println("No stack traces available");
            return;
        }
        for (Entry<Thread, StackTraceElement[]> entry : map.entrySet())
            printStackTrace(writer, entry.getKey(), entry.getValue());
        writer.flush();
    }

    private static void printStackTrace(PrintWriter writer, Thread thread, StackTraceElement[] trace) {
        try {
            writer.println(thread.toString() + ":");
            for (int i = 0; i < trace.length; i++)
                writer.println("\tat " + trace[i]);
        } catch (Exception e) {
            writer.println("\t*** Exception printing stack trace: " + e);
        }
        writer.flush();
    }
}

Related

  1. printStackTrace(Throwable throwable)
  2. printStackTrace(Throwable throwable)
  3. printStackTraceAsHtml(Throwable t)
  4. printStackTraceElement(StackTraceElement element, StringBuilder buffer)
  5. printStackTraceHTML(Throwable e)
  6. printStackTraceToOutputStream(Throwable t, OutputStream out)
  7. printStackTraceToString(final Throwable t)
  8. printStackTraceToString(Throwable aThrowable)
  9. printStackTraceUsingStream(Throwable throwable)