Java tutorial
//package com.java2s; /* * Copyright 2015 the original author or authors. * @https://github.com/scouter-project/scouter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.lang.management.ManagementFactory; import java.lang.management.ThreadInfo; import java.lang.management.ThreadMXBean; public class Main { public static String getThreadStack(long id) { ThreadMXBean tmb = ManagementFactory.getThreadMXBean(); ThreadInfo f = tmb.getThreadInfo(id, 500); if (f == null) return null; return getStackTrace(f.getStackTrace()); } public static String getThreadStack() { return getStackTrace(Thread.currentThread().getStackTrace()); } public static String getStackTrace(StackTraceElement[] se) { return getStackTrace(se, 0); } public static String getStackTrace(StackTraceElement[] se, int skip) { if (se == null || se.length <= skip) return ""; String CRLF = System.getProperty("line.separator"); StringBuffer sb = new StringBuffer(); for (int i = skip; i < se.length; i++) { if (sb.length() > 0) { sb.append(CRLF); } sb.append(se[i]); } return sb.toString(); } public static String getStackTrace(Throwable t) { String CRLF = System.getProperty("line.separator"); StringBuffer sb = new StringBuffer(); sb.append(t.toString() + CRLF); StackTraceElement[] se = t.getStackTrace(); if (se != null) { for (int i = 0; i < se.length; i++) { if (se[i] != null) { sb.append("\t" + se[i].toString()); if (i != se.length - 1) { sb.append(CRLF); } } } } return sb.toString(); } public static void getStackTrace(StringBuffer sb, Throwable t, int max) { if (t == null) return; if (max <= 0) { max = 10000; } String CRLF = System.getProperty("line.separator"); sb.append(t); StackTraceElement[] se = t.getStackTrace(); if (se != null && se.length > 0) { for (int i = 0; i < se.length && i < max; i++) { sb.append(CRLF); sb.append("\t" + se[i]); } if (max < se.length) { sb.append(CRLF + "\t...more lines " + (se.length - max)); } } else { sb.append(CRLF + "\tno stack info "); } } }