Java Thread Dump Using JSP

Java

Below JSP code can be used in any webapplication to create on the fly thread dump with out accessing the machine to execute any commands like CTRL+BREAK, kill -3 etc. Just save the code to a JSp file and access it from the Application URL.
E.g: If you have saved the file threaddump.jsp in WEB-INF directory of the application then access http://AppURl:PORT/threaddump.jsp to get the thread dump /Stack trace online on your webpage.

 

<%@ page language="java" import="java.util.*,java.lang.Thread.*" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%--
Author:- Ramakanta(rks2286(at)gmail(dot)com)
Date Created: Mar 14 2010
PurPose: Online Java Thread Dump
Minimum Java version Required: 1.5.x
--%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="CACHE-CONTROL" content="NO-CACHE">
<title>Thread Dump</title>
</head>
<body>

<table width="100%" border="1" cellspacing="0" cellpadding="3" bordercolor="#000000">
<tr>
<td bgcolor="#E7E7EF" bordercolor="#000000" align="center" nowrap>
<font face="Verdana" size="+1">Thread Dumps&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font>
</td>
</tr>

<tr>
<td bgcolor="#E7E7EF" bordercolor="#000000">

<%
out.print("---------------------------START-----------------------------------------<br>");
out.print("Generating Thread-Dump At:" + (new java.util.Date()).toString() + "<BR>");
out.println("---------------------------------------------------------------------<br>");

Map map = Thread.getAllStackTraces();

Iterator itr = map.keySet().iterator();
while (itr.hasNext()) {
Thread t = (Thread)itr.next();
StackTraceElement[] elem = (StackTraceElement[])map.get(t);

//Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();

//Iterator<Thread> itr = map.keySet().iterator();
//while (itr.hasNext()) {
//    Thread t = itr.next();
//StackTraceElement[] elem = map.get(t);
out.print("\"" + t.getName() + "\"");
out.print(" Priority=" + t.getPriority());
out.print(" Thread Id=" + t.getId());
State s = t.getState();
String state = null;
String color = "000000";
String GREEN = "00FF00";
String RED = "FF0000";
String ORANGE = "FCA742";
switch(s) {
case NEW: state ="NEW"; color = GREEN; break;
case BLOCKED: state = "BLOCKED"; color = RED; break;
case RUNNABLE: state = "RUNNABLE"; color = GREEN; break;
case TERMINATED: state = "TERMINATED"; break;
case TIMED_WAITING: state = "TIME WAITING"; color = ORANGE; break;
case WAITING: state = "WAITING"; color = RED; break;
}
out.print("<font color=\"" + color + "\"> In State :</font>");
out.println(" " + state + "<BR>");
for (int i=0; i < elem.length; i++) {
out.println("  at ");
out.print(elem[i].toString());
out.println("<BR>");
}
out.println("--------------------------------------------------------------------------<br>");
}
out.print("----------------------------FINISH--------------------------------------<br>");
out.print("Generated Thread-Dump At:" + (new java.util.Date()).toString() + "<BR>");
out.println("---------------------------------------------------------------------<br>");
%>
</td>
</tr>
</table>
</body>
</html>

Note: Minimum Java version required to run above JSP code is 1.5x.

If you have lower version of java running in your App Server then you need to get below JSP code which will RUN OK in 1.4.x Java too, though the details will not be that good/indepth.

 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%--
Author:- Ramakanta(rks2286(at)gmail(dot)com)
Date Created: Mar 14 2010
PurPose: Online Java Thread Dump
Java required: 1.4.x
--%>



<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="CACHE-CONTROL" content="NO-CACHE">
<title>Thread Lister</title>
</head>
<body>

<table width="100%" border="1" cellspacing="0" cellpadding="3" bordercolor="#000000">
<tr>
<td bgcolor="#E7E7EF" bordercolor="#000000" align="center" nowrap>
<font face="Verdana" size="+1">Thread Lister&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</font>
</td>
</tr>

<tr>
<td bgcolor="#E7E7EF" bordercolor="#000000">
<%@ page import="java.io.*" %>
<%

out.print("<hr />");
out.print("<p align=center>"+"Application Java Thread Dump"+"<br />");
out.print("Generating Thread-Dump At:" + (new java.util.Date()).toString() + "<br />");
out.println("</p><hr />"+"<br />");

// Get the top level thread group
ThreadGroup adam = getAdam(Thread.currentThread().getThreadGroup());
// Get the count of active threads in the system
int num = adam.activeCount();
// Get all of the active threads in the system
Thread list[] = new Thread[num];
int x = adam.enumerate(list);

// Display all of the active threads in the system
for (int i = 0; i < x; i++)
{
if (list[i] == null) continue;
String threadName = list[i].getName();
String groupName = list[i].getThreadGroup().getName();
String stack = list[i].getThreadGroup().toString();
//State s = list[i].getState();
out.print("group:" + groupName
+ ", thread:" + threadName
+ ", priority:" + list[i].getPriority()
+ ", daemon:" + (list[i].isDaemon() ? "Yes" : "No")
+ ", alive:" + (list[i].isAlive() ? "Yes" : "No")
+",Is Interrupted:"+(list[i].isInterrupted() ? "Yes" : "No")
//+",State:"+(list[i].Thread.holdsLock(writer) ? "Yes" : "No")
+"<br />"+"ThreadGroup:"+ stack+"<br />"
);

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
PrintStream writer = new PrintStream(bytes, true);
System.setOut(writer);
System.setErr(writer);
//(new Throwable()).printStackTrace( writer );
//boolean abc = assert Thread.holdsLock(writer);
//out.print("ha"+abc);
//Thread.dumpStack();
out.print("<br />");
list[i].dumpStack();
String str = bytes.toString();
str = str.replaceAll("\n","<br/>    ");
out.print("Stack Dump:" + str

+"<hr />");
}
//Thread.dumpStack();
//String line = null;
//try{
//   while((line = reader.readLine()) != null) out.print(line + "<br/>");
//}catch(IOException ioe) {System.out.println(ioe.getMessage());}

out.print("<p align=center>Finish<br/>");
out.print("Application Java Thread Dump<br/>");
out.print("Completed Thread-Dump At:" + (new java.util.Date()).toString()+"<br/>");
out.println("</p><hr />"+"<br />");

%>
<%--!
BufferedReader reader;
public void jspInit(){
// File errFile = new File(getServletContext().getRealPath("/StdErr.txt"));
try{
File errFile = File.createTempFile("StrErr",".txt");
reader = new BufferedReader(new FileReader(errFile));
PrintStream ps = new PrintStream(errFile);
System.setErr(ps);
}catch(IOException ioe) {System.out.println(ioe.getMessage());}
}
private ThreadGroup getAdam (ThreadGroup tg)
{
ThreadGroup parent = tg.getParent();
if (parent == null)
return tg;

return getAdam(parent);
}
--%>




<%!
// Recursively calls itself to find the top level thread group
private static ThreadGroup getAdam (ThreadGroup tg)
{
ThreadGroup parent = tg.getParent();
if (parent == null)
return tg;

return getAdam(parent);
}
%>

</td>
</tr>
</table>
</body>
</html>

In case of any ©Copyright or missing credits issue please check CopyRights page for faster resolutions.

Leave a Reply