轻松获取jvm线程的代码
<%@ page import="java.util.Iterator" %> <%@ page import="java.util.Map" %> <%@ page import="java.util.HashMap" %> <%@ page contentType="text/html;charset=UTF-8" session="false" language="java"%> <html> <head> <title>Threads</title> <script> function toggleStacks(id) { var ele = document.getElementById(id); if(!ele.style.display || ele.style.display != "none") { ele.style.display = "none"; } else { ele.style.display = "block"; } return false; } </script> <style type="text/css"> li { list-style-type: none; display: inline; } </style> </head> <body> <a href="javascript:void(0)" onclick="return toggleStacks(‘system-res‘);">resource</a><br/> <div id="system-res"> <ul> <li>freeMemory: <%=Runtime.getRuntime().freeMemory()/(1024*1024)%>M;</li> <li>totalMemory: <%=Runtime.getRuntime().totalMemory()/(1024*1024)%>M;</li> <li>maxMemory: <%=Runtime.getRuntime().maxMemory()/(1024*1024)%>M;</li> </ul> </div> <% Map<Thread, StackTraceElement[]> allStacks = Thread.getAllStackTraces(); Map<Thread.State, Map<Thread, StackTraceElement[]>> classifyThreads = new HashMap<Thread.State, Map<Thread, StackTraceElement[]>>(); if (allStacks != null) { Iterator<Map.Entry<Thread, StackTraceElement[]>> stackIterator = allStacks.entrySet().iterator(); while (stackIterator.hasNext()) { Map.Entry<Thread, StackTraceElement[]> stackEntry = stackIterator.next(); Thread thread = stackEntry.getKey(); Thread.State state = thread.getState(); StackTraceElement[] traceElements = stackEntry.getValue(); Map<Thread, StackTraceElement[]> threadStacks = classifyThreads.get(state); if(threadStacks == null) { threadStacks = new HashMap<Thread, StackTraceElement[]>(); classifyThreads.put(state, threadStacks); } threadStacks.put(thread, traceElements); } } for(Thread.State state : Thread.State.values()) { Map<Thread, StackTraceElement[]> threadStacks = classifyThreads.get(state); if(threadStacks != null) { Iterator<Map.Entry<Thread, StackTraceElement[]>> stackIterator = threadStacks.entrySet().iterator(); out.println("<b>"+state.name()+"("+threadStacks.size()+")</b><br/><hr/>"); while (stackIterator.hasNext()) { Map.Entry<Thread, StackTraceElement[]> stackEntry = stackIterator.next(); Thread thread = stackEntry.getKey(); StackTraceElement[] traceElements = stackEntry.getValue(); out.println("<pre>"); out.println("<a href=\"javascript:void(0);\" onclick=\"return toggleStacks(‘thread-"+thread.getId()+"‘);\">" + thread + "-" + thread.getState() + ":" + thread.getId() + "(" + traceElements.length + ")</a>"); if(traceElements != null) { out.println("<div id=\"thread-"+thread.getId()+"\" style=\"display:none;\">"); for(StackTraceElement stack : traceElements) { out.println(" " + stack + " - " + stack.getFileName()); } out.println("<div>"); } out.println("</pre>"); } out.println("<br/>"); } } %> </body> </html>
实现类似jstack的功能
时间: 2024-11-05 22:35:45