用JMX调试Java应用程序

如果不用jconsole,我们也可以直接用JMX来编程实现jconsole的所有功能。
1. Java应用启动时增加下面的参数:
-Dcom.sun.management.jmxremote.port=6789
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
这样Java程序起来后会多起一个"JMX server connection timeout"线程和一些RMI线程。

2.写代码连到6789端口,得到所有线程的堆栈信息。
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;


/**
* @author fanrey
*
*/
public class JMXRemoteTest {

/**
* @param args
*/
public static void main(String[] args) {
String hostName = "127.0.0.1";
String portNum = "6789";
JMXServiceURL u;
try {
u = new JMXServiceURL(
"service:jmx:rmi:///jndi/rmi://" + hostName + ":" + portNum + "/jmxrmi");
JMXConnector c = JMXConnectorFactory.connect(u);

MBeanServerConnection conn = c.getMBeanServerConnection();
MemoryMXBean memoryMXBean = ManagementFactory.newPlatformMXBeanProxy(conn, ManagementFactory.MEMORY_MXBEAN_NAME, MemoryMXBean.class);
MemoryUsage heap = memoryMXBean.getHeapMemoryUsage();
MemoryUsage nonheap = memoryMXBean.getNonHeapMemoryUsage();
System.out.println(heap);
System.out.println(nonheap);

ThreadMXBean tb = ManagementFactory.newPlatformMXBeanProxy(conn, ManagementFactory.THREAD_MXBEAN_NAME, ThreadMXBean.class);
System.out.println("Thread count: "+tb.getThreadCount());
long[] ct = tb.getAllThreadIds();
for (int i = 0; i < ct.length; i++) {
ThreadInfo ti = tb.getThreadInfo(ct[i], Integer.MAX_VALUE);
if (ti != null) {
System.out.println("Thread name and ID:........" + ti.getThreadName() + " (" + ct[i] + ")");
System.out.println("Thread state:.............." + ti.getThreadState().toString());
System.out.print("Lock:......................Name=" + ti.getLockName());
System.out.print(" OwnerID=" + ti.getLockOwnerId());
System.out.println(" OwnerName=" + ti.getLockOwnerName());
System.out.println("Thread blocked:............" + ti.getBlockedCount() + " times / " + ti.getBlockedTime());
System.out.println("Thread waited:............." + ti.getWaitedCount() + " times / " + ti.getWaitedTime());

StackTraceElement[] ste = ti.getStackTrace();
if (ste.length > 0) {
for (int j = 0; j < ste.length; j++) {
System.out.println("\t" + ste[j]);
}
}
System.out.println("- - - - - -");
} else {
System.out.println("Thread name and ID:........(" + ct[i] + ") (Thread has died.)");
}
}
} catch (Exception e) {
e.printStackTrace();
}



}

}

你可能感兴趣的:(用JMX调试Java应用程序)