• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 916
  • Last Modified:

Thread Dump Using SUN JDK1.4.2_13 using JSP

Hi All,

I want a JSP which will give me the Thread Dump of running Java processes.
I'm using Sun JDK 1.4.2_13 .

I have below JSP code which requires 1.5 Java to run properly.
I want Thread Dump JSP file which will run on 1.4.2_13 Please help.

For your reference I'm putting the code for 1.5 Java
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>");
			}

Open in new window

0
Ramakanta Sahoo
Asked:
Ramakanta Sahoo
  • 12
  • 6
  • 5
  • +1
2 Solutions
 
Gibu GeorgeCTOCommented:
Remove the generics and add the type casting
like this

Map map = Thread.getAllStackTraces();

Iterator itr = map.keySet().iterator();
      while (itr.hasNext()) {
                  Thread t = (Thread)itr.next();
                  StackTraceElement[] elem = (StackTraceElement[])map.get(t);
0
 
Ramakanta SahooAuthor Commented:
Hi,

Its showing compile Error..
can somebody help me out here.


org.apache.jasper.JasperException: Unable to compile class for JSP
 
An error occurred at line: 28 in the jsp file: /stack.jsp
Generated servlet error:
/home/rsahoo/programs/jakarta-tomcat-5.0.28/work/Catalina/localhost/ecpadmin/org/apache/jsp/stack_jsp.java:107: cannot resolve symbol
symbol  : method getAllStackTraces ()
location: class java.lang.Thread
	Map map = Thread.getAllStackTraces();
                        ^
 
 
An error occurred at line: 28 in the jsp file: /stack.jsp
Generated servlet error:
/home/rsahoo/programs/jakarta-tomcat-5.0.28/work/Catalina/localhost/ecpadmin/org/apache/jsp/stack_jsp.java:122: cannot resolve symbol
symbol  : method getId ()
location: class java.lang.Thread

Open in new window

0
 
Gibu GeorgeCTOCommented:
The getAllStackTraces and getId  mehtods are added in Java 1.5.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Ramakanta SahooAuthor Commented:
Yes I know that for this reason only i have posted the question on how to achieve the same using JDK 1.4.2_13.
Any help appreciated.
0
 
Ramakanta SahooAuthor Commented:
Yes , I have seen it before.
Its of Java 1.5 again.

MY SERVER HAVE JDK 1.4.2_13 .
I NEED FOR JSP.
0
 
Ramakanta SahooAuthor Commented:
I NEED IT FROM INSIDE THE SERVER.
SO THAT WHEN I WILL ACCESS THE JSP FILE IT WILL THROW ME THE THREAD DUMP .

ANY BODY KNOW HOW TO DO IT USING JDK1.4.2_13???????????????
0
 
mrcoffee365Commented:
Shouting is not a great way to communicate.  I was tempted not to respond at all, which I imagine is how a lot of experts are reacting.

However, assuming that you are new to EE and to Internet communication, here is more information about how to get stack trace info from older JDKs:
http://java.sun.com/developer/technicalArticles/Programming/Stacktrace/

Programmatically, you can get the ThreadGroup for the current thread, then get all subthreads of the outer threadgroup and call dumpStack on each of them.

Try some of the examples and see how they work for you.  Looking at the Thread Java API and the ThreadGroup API will probably help you.
0
 
Ramakanta SahooAuthor Commented:
Sorry for my idiotic shouting, may be i was mad and pissed off  that time working with old unsupported 1.4.2_13 JDK.
Sorry Again for the same.
I have code like below can you please let me know what should i add to use the dumpStack method.
Am not able to get it done correctly.

Thank You.
<%
           // 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();
            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")
                    +",To String:"+ stack
                    //+",Holds Lock:"+(list[i].dumpStack())
                    
                    +"<hr />");
        
                         }
    %>
    
    
    
    
    <%! 
    // 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);
    }
    %>

Open in new window

0
 
rrzCommented:
>I have code like below can you please let me know what should i add to use the dumpStack method.
The dumpStack method is static. So it probably doesn't do what you want it to do. Anyway try the following JSP.  
<%@ page import="java.io.*" %>
<%
           // 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();
            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")
                    + ",To String:" + stack + "<br/>");
        }
        Thread.dumpStack();
        String line = null;
        try{
            while((line = reader.readLine()) != null) out.print(line + "<br/>");
        }catch(IOException ioe) {System.out.println(ioe.getMessage());}
    %>
    <%! 
       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);
       }
    %>

Open in new window

0
 
mrcoffee365Commented:
Ah -- it turns out that dumpStack will only write to stderr.   It is potentially a mess, but you can redirect stdout and stderr to a local printstream and display that in your Web page.  This isn't recommended, but it ran :o)

            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")
                    +",To String:"+ stack
                    +"<hr />");

                  ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                  PrintStream writer = new PrintStream(bytes, true);
                  System.setOut(writer);
                  System.setErr(writer);
                  //(new Throwable()).printStackTrace( writer );
                  list[i].dumpStack();
                  String str = bytes.toString();

            out.print(",Holds Lock:" + str
                   
                    +"<hr />");
0
 
mrcoffee365Commented:
However, on further research, dumpStack is static, and only shows the current thread.

So the alternative is to implement calls to the JVM debugger interface, which is a great deal of work.  Essentially, you're writing a little debugger which you will then call from your JSP page.   You'll have to compile C programs and call them.  An example is here:
http://codeguru.earthweb.com/java/articles/327.shtml
It seems unlikely you want to go that route.

Another complicated method, but possibly more approachable, is to follow the advice from this discussion:
http://www.theserverside.com/discussions/thread.tss?thread_id=43163

The advice for pre jdk 1.5 is:
"The one method that works with all Sun VMs (so far) is to write a little JNI lib so that you can get the process ID of your VM (e.g on linux, call getpid()). Then just run kill -3 <pid>, or on windows use SendSignal.exe (google for that executable). Unfortunately the thread dump is going to be on stderr, so you had better know where that stream is going (hopefully not /dev/null)."

So the answer might be -- it's not possible in a reasonable amount of development time.  Or you can dig in and try one of the above methods.
0
 
Ramakanta SahooAuthor Commented:
Hi RRZ and MRCOFEE thatk you all so much for the help.

While compiling I'm getting below error can you tell me what shall i do
org.apache.jasper.JasperException: Unable to compile class for JSP
 
An error occurred at line: 73 in the jsp file: /ThreadLister.jsp
Generated servlet error:
/home/rsahoo/programs/jakarta-tomcat-5.0.28/work/Catalina/localhost/ecpadmin/org/apache/jsp/ThreadLister_jsp.java:19: cannot resolve symbol
symbol  : constructor PrintStream (java.io.File)
location: class java.io.PrintStream
                 PrintStream ps = new PrintStream(errFile);
                                  ^
1 error
 
 
 
	org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:84)
	org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:332)

Open in new window

0
 
Gibu GeorgeCTOCommented:
PrintStream takes output stream as parameter not file
you can give the jsp implicit object out in place to print to the jsp page
0
 
Ramakanta SahooAuthor Commented:
I have exactly copied RRZ's new addon code with replacement of out.print statement from MRCOFEE.

Please help Am I missing something to import except java.io.*
0
 
Gibu GeorgeCTOCommented:
In that example mrcofee has done it like this

ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                  PrintStream writer = new PrintStream(bytes, true);
Not passing file to PrintStream it is a ByteArrayOutputStream
0
 
mrcoffee365Commented:
You can either go with rrz's code or the code I gave you.   You created an error by making mistakes in mixing them.

My code works and runs, although as I mentioned, dumpStack is static.  RRZ's code also won't give you a stack trace except from the current thread.  In fact, it tries to do exactly the same thing, but with more lines of code.
0
 
Ramakanta SahooAuthor Commented:
I tried also RRZ's code only but it gives me the same error.
Is there anything missing out in RRZ's code please help
0
 
Ramakanta SahooAuthor Commented:
Some how its working now i've a big task of awarding points. :)
SO I'm sharing it I think you guys wont mind if I share. Please reply in case you have something to suggest.
0
 
Ramakanta SahooAuthor Commented:
Sorry gibu_george: I wanted to award some points to you too but total points is 50 and I can minimum allocate 20 points so splitted it into 20+30=50.
Please dont mind thank you somuch for helping
0
 
mrcoffee365Commented:
I'm very surprised to see a B -- we gave you working code and detailed explanations.  Giving an A does not cost you anything, and makes a big difference to the experts in terms of return on the time we spent on it.  Too bad.
0
 
rrzCommented:
mrcoffee, I agree with you. You are right on all counts.  
But I had fun anyway. Below is a final code using your code and with formatting.
<%@ page import="java.io.*" %>
<%
        ThreadGroup adam = getAdam(Thread.currentThread().getThreadGroup());
        int num = adam.activeCount();
       	// Get all of the active threads in the system
        Thread list[] = new Thread[num];
        int x = adam.enumerate(list);
        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();
            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")
                    + ",To String:" + stack + "<br/>");
        }
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            PrintStream writer = new PrintStream(bytes, true);
            System.setErr(writer);
            Thread.dumpStack();
            String str = bytes.toString();
            str = str.replaceAll("\n","<br/>&nbsp;&nbsp;&nbsp;&nbsp;");
            out.print(str);
    %>
    <%! 
       private ThreadGroup getAdam (ThreadGroup tg)
       {
        ThreadGroup parent = tg.getParent();
        if (parent == null)
            return tg;
        return getAdam(parent);
       }
    %>

Open in new window

0
 
Ramakanta SahooAuthor Commented:
Thank you RRZ .
Sory for giving B
0
 
Ramakanta SahooAuthor Commented:
Though the answers were great , I gave it B because it cannot catch the state of a thread stuck runnable etc.
It cant not show deadlocked threads.
I think this is possible in 1.5 only.
I hope you can understand.
0
 
mrcoffee365Commented:
No, the fact that we gave you the right answer, and it wasn't what you wanted to hear, does not merit a B.  Check the FAQ again -- a B is when someone doesn't help you much, but gives you some links to documentation.

It doesn't make sense to give a low grade to people who've spent a lot of time helping you because you are not happy with the limitations of the old release of the Java JDK.

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 12
  • 6
  • 5
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now