1 /***
2 * Copyright 2003-2010 Terracotta, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package net.sf.ehcache.constructs.nonstop;
18
19 import java.lang.management.ManagementFactory;
20 import java.lang.management.ThreadInfo;
21 import java.lang.management.ThreadMXBean;
22 import java.util.ArrayList;
23 import java.util.List;
24
25 public abstract class ThreadDump {
26 private static final String NEWLINE = System.getProperty("line.separator", "\n");
27
28 public static List<ThreadInformation> getThreadDump() {
29 List<ThreadInformation> rv = new ArrayList<ThreadInformation>();
30 ThreadMXBean tbean = ManagementFactory.getThreadMXBean();
31 for (long id : tbean.getAllThreadIds()) {
32 ThreadInfo tinfo = tbean.getThreadInfo(id);
33 if (tinfo != null) {
34 rv.add(new ThreadInformation(tinfo.getThreadId(), tinfo.getThreadName()));
35 }
36 }
37 return rv;
38 }
39
40 public static String takeThreadDump() {
41 StringBuilder rv = new StringBuilder();
42 ThreadMXBean tbean = ManagementFactory.getThreadMXBean();
43 for (long id : tbean.getAllThreadIds()) {
44 ThreadInfo tinfo = tbean.getThreadInfo(id, Integer.MAX_VALUE);
45 if (tinfo != null) {
46 rv.append(tinfo).append(NEWLINE);
47 for (StackTraceElement e : tinfo.getStackTrace()) {
48 rv.append(" at ").append(e).append(NEWLINE);
49 }
50 rv.append(NEWLINE);
51 }
52 }
53 return rv.toString();
54 }
55
56 public static class ThreadInformation {
57 private final long threadId;
58 private final String threadName;
59
60 public ThreadInformation(long threadId, String name) {
61 super();
62 this.threadId = threadId;
63 this.threadName = name;
64 }
65
66 public long getThreadId() {
67 return threadId;
68 }
69
70 public String getThreadName() {
71 return threadName;
72 }
73
74 @Override
75 public int hashCode() {
76 return ((int) threadId) ^ ((int) (threadId >>> 32));
77 }
78
79 @Override
80 public boolean equals(Object obj) {
81 if (this == obj) {
82 return true;
83 } else if (obj instanceof ThreadInformation) {
84 return threadId == ((ThreadInformation) obj).threadId;
85 } else {
86 return false;
87 }
88 }
89
90 }
91 }