java監控之ManagementFactory分析


 

The  ManagementFactory class is a factory class for getting managed beans for the Java platform. This class consists of static methods each of which returns one or more  platform MXBeans representing the management interface of a component of the Java virtual machine.

 

Platform MXBeans

A platform MXBean is a managed bean that conforms to the JMX Instrumentation Specification and only uses a set of basic data types. A JMX management application and the platform MBeanServer can interoperate without requiring classes for MXBean specific data types. The data types being transmitted between the JMX connector server and the connector client are open types and this allows interoperation across versions. See the specification of MXBeans for details.

Each platform MXBean is a PlatformManagedObject and it has a unique ObjectName for registration in the platform MBeanServer as returned by by the getObjectName method.

An application can access a platform MXBean in the following ways:

1. Direct access to an MXBean interface
2. Indirect access to an MXBean interface via MBeanServer
  • Go through the platform MBeanServer to access MXBeans locally or a specific MBeanServerConnection to access MXBeans remotely. The attributes and operations of an MXBean use only JMX open types which include basic data types, CompositeData, and TabularData defined in OpenType. The mapping is specified in theMXBean specification for details.

The getPlatformManagementInterfaces method returns all management interfaces supported in the Java virtual machine including the standard management interfaces listed in the tables below as well as the management interfaces extended by the JDK implementation.

A Java virtual machine has a single instance of the following management interfaces:

Management Interface ObjectName
ClassLoadingMXBean java.lang:type=ClassLoading
MemoryMXBean java.lang:type=Memory
ThreadMXBean java.lang:type=Threading
RuntimeMXBean java.lang:type=Runtime
OperatingSystemMXBean java.lang:type=OperatingSystem
PlatformLoggingMXBean java.util.logging:type=Logging

A Java virtual machine has zero or a single instance of the following management interfaces.

Management Interface ObjectName
CompilationMXBean java.lang:type=Compilation

A Java virtual machine may have one or more instances of the following management interfaces.

Management Interface ObjectName
GarbageCollectorMXBean java.lang:type=GarbageCollector,name=collector's name
MemoryManagerMXBean java.lang:type=MemoryManager,name=manager's name
MemoryPoolMXBean java.lang:type=MemoryPool,name=pool's name
BufferPoolMXBean java.nio:type=BufferPool,name=pool name

實例1:

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.Set;
import javax.management.AttributeNotFoundException;
import javax.management.BadAttributeValueExpException;
import javax.management.BadBinaryOpValueExpException;
import javax.management.BadStringOperationException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.InvalidApplicationException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.QueryExp;
import javax.management.ReflectionException;
import javax.management.RuntimeMBeanException;

public class JMXUtils {

    private final static MBeanServer DEFAULT_MBEAN_SERVER = ManagementFactory
            .getPlatformMBeanServer();

    public static long getYongGC() {
        return getYoungGC(DEFAULT_MBEAN_SERVER);
    }

    public static long getFullGC() {
        return getFullGC(DEFAULT_MBEAN_SERVER);
    }

    public static long findLoadedClass() {
        return findLoadedClass(DEFAULT_MBEAN_SERVER);
    }

    public static long getYoungGC(MBeanServerConnection mbeanServer) {
        try {
            ObjectName objectName;
            if (mbeanServer.isRegistered(new ObjectName("java.lang:type=GarbageCollector,name=ParNew"))) {
                objectName = new ObjectName("java.lang:type=GarbageCollector,name=ParNew");
            } else if (mbeanServer.isRegistered(new ObjectName("java.lang:type=GarbageCollector,name=Copy"))) {
                objectName = new ObjectName("java.lang:type=GarbageCollector,name=Copy");
            } else {
                objectName = new ObjectName("java.lang:type=GarbageCollector,name=PS Scavenge");
            }
            return (Long) mbeanServer.getAttribute(objectName , "CollectionCount");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static long getFullGC(MBeanServerConnection mbeanServer) {
        try {
            ObjectName objectName;
            if (mbeanServer.isRegistered(new ObjectName("java.lang:type=GarbageCollector,name=ConcurrentMarkSweep"))) {
                objectName = new ObjectName("java.lang:type=GarbageCollector,name=ConcurrentMarkSweep");
            } else if (mbeanServer.isRegistered(new ObjectName("java.lang:type=GarbageCollector,name=MarkSweepCompact"))) {
                objectName = new ObjectName("java.lang:type=GarbageCollector,name=MarkSweepCompact");
            } else {
                objectName = new ObjectName("java.lang:type=GarbageCollector,name=PS MarkSweep");
            }
            return (Long) mbeanServer.getAttribute(objectName , "CollectionCount");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static long findLoadedClass(MBeanServerConnection mBeanServer) {
        try {
            return (Long) (mBeanServer.getAttribute(new ObjectName(
                    "java.lang:type=ClassLoading"), "TotalLoadedClassCount"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void traceOneDomain(String doMain,
            MBeanServerConnection mBeanServer)
            throws MalformedObjectNameException, IntrospectionException,
            InstanceNotFoundException, AttributeNotFoundException,
            ReflectionException, MBeanException, IOException {
        
        Set<ObjectInstance> set = mBeanServer.queryMBeans(new ObjectName(doMain + ":*"), new QueryExp() {
            private static final long serialVersionUID = 1L;

            @Override
            public boolean apply(ObjectName name)
                    throws BadStringOperationException,
                    BadBinaryOpValueExpException,
                    BadAttributeValueExpException, InvalidApplicationException {
                return true;
            }

            @Override
            public void setMBeanServer(MBeanServer s) {}
        });
        for (ObjectInstance objectInstance : set) {
            System.out.println("\t\t\t" + objectInstance.getObjectName() + "\t"
                    + objectInstance.getClassName());
            traceMebeanInfo(mBeanServer, objectInstance.getObjectName());
        }
    }

    public static void traceMebeanInfo(MBeanServerConnection mBeanServer,
            ObjectName objectName) throws IntrospectionException,
            InstanceNotFoundException, MalformedObjectNameException,
            ReflectionException, AttributeNotFoundException, MBeanException,
            IOException {
        MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(objectName);
        MBeanAttributeInfo[] mBeanAttributes = mBeanInfo.getAttributes();

        System.out.println("\t\t\tMBeanInfos : ");
        for (MBeanAttributeInfo mBeanAttribute : mBeanAttributes) {
            try {
                System.out.println("\t\t\t\t\t"
                        + mBeanAttribute.getName()
                        + "\t"
                        + mBeanAttribute.getType()
                        + "\tvalue = >"
                        + mBeanServer.getAttribute(objectName,
                                mBeanAttribute.getName()));
            } catch (RuntimeMBeanException e) {
                if (e.getCause() instanceof UnsupportedOperationException) {
                    System.out.println("\t\t\t\t\t" + mBeanAttribute.getName()
                            + "\t" + mBeanAttribute.getType()
                            + "\tvalue = > value not supported");
                }
            }

        }
    }

    public static void traceAll(MBeanServerConnection mBeanServer)
            throws MalformedObjectNameException, IntrospectionException,
            InstanceNotFoundException, AttributeNotFoundException,
            ReflectionException, MBeanException, IOException {
        System.out.println("MBean count = " + mBeanServer.getMBeanCount());
        String[] domains = mBeanServer.getDomains();
        for (String domain : domains) {
            System.out.println("\tbegin trace domain -> " + domain);
            traceOneDomain(domain, mBeanServer);
        }
    }
}

實例2:

<%@ page import="java.lang.management.*" %>
<%@ page import="java.util.*" %>
<html>
<head>
  <title>JVM Memory Monitor</title>
</head>
<body>
<table border="0" width="100%">
    <tr><td colspan="2" align="center"><h3>Memory MXBean</h3></td></tr>
    <tr><td width="200">Heap Memory Usage</td><td><%=ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()%></td></tr>
    <tr><td>Non-Heap Memory Usage</td><td><%=ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage()%></td></tr>
    <tr><td colspan="2">&nbsp;</td></tr>
    <tr><td colspan="2" align="center"><h3>Memory Pool MXBeans</h3></td></tr>
<%
        Iterator iter = ManagementFactory.getMemoryPoolMXBeans().iterator();
        while (iter.hasNext()) {
            MemoryPoolMXBean item = (MemoryPoolMXBean) iter.next();
%>
<tr><td colspan="2">
    <table border="0" width="100%" style="border: 1px #98AAB1 solid;">
        <tr><td colspan="2" align="center"><b><%= item.getName() %></b></td></tr>
        <tr><td width="200">Type</td><td><%= item.getType() %></td></tr>
        <tr><td>Usage</td><td><%= item.getUsage() %></td></tr>
        <tr><td>Peak Usage</td><td><%= item.getPeakUsage() %></td></tr>
        <tr><td>Collection Usage</td><td><%= item.getCollectionUsage() %></td></tr>
    </table>
</td></tr>
<tr><td colspan="2">&nbsp;</td></tr>
<%} %>
</table>
</body>
</html>

 

另外的方式:

內存監控的方法: 

1. jmap -heap pid
查看java 堆(heap)使用情況

using thread-local object allocation.
Parallel GC with 4 thread(s) //GC 方式

Heap Configuration: //堆內存初始化配置
MinHeapFreeRatio=40 //對應jvm啟動參數-XX:MinHeapFreeRatio設置JVM堆最小空閑比率(default 40)
MaxHeapFreeRatio=70 //對應jvm啟動參數 -XX:MaxHeapFreeRatio設置JVM堆最大空閑比率(default 70)
MaxHeapSize=512.0MB //對應jvm啟動參數-XX:MaxHeapSize=設置JVM堆的最大大小
NewSize = 1.0MB //對應jvm啟動參數-XX:NewSize=設置JVM堆的‘新生代’的默認大小
MaxNewSize =4095MB //對應jvm啟動參數-XX:MaxNewSize=設置JVM堆的‘新生代’的最大大小
OldSize = 4.0MB //對應jvm啟動參數-XX:OldSize=<value>:設置JVM堆的‘老生代’的大小
NewRatio = 8 //對應jvm啟動參數-XX:NewRatio=:‘新生代’和‘老生代’的大小比率
SurvivorRatio = 8 //對應jvm啟動參數-XX:SurvivorRatio=設置年輕代中Eden區與Survivor區的大小比值
PermSize= 16.0MB //對應jvm啟動參數-XX:PermSize=<value>:設置JVM堆的‘永生代’的初始大小
MaxPermSize=64.0MB //對應jvm啟動參數-XX:MaxPermSize=<value>:設置JVM堆的‘永生代’的最大大小

Heap Usage: //堆內存分步
PS Young Generation
Eden Space: //Eden區內存分布
capacity = 20381696 (19.4375MB) //Eden區總容量
used = 20370032 (19.426376342773438MB) //Eden區已使用
free = 11664 (0.0111236572265625MB) //Eden區剩余容量
99.94277218147106% used //Eden區使用比率
From Space: //其中一個Survivor區的內存分布
capacity = 8519680 (8.125MB)
used = 32768 (0.03125MB)
free = 8486912 (8.09375MB)
0.38461538461538464% used
To Space: //另一個Survivor區的內存分布
capacity = 9306112 (8.875MB)
used = 0 (0.0MB)
free = 9306112 (8.875MB)
0.0% used
PS Old Generation //當前的Old區內存分布
capacity = 366280704 (349.3125MB)
used = 322179848 (307.25464630126953MB)
free = 44100856 (42.05785369873047MB)
87.95982001825573% used
PS Perm Generation //當前的 “永生代” 內存分布
capacity = 32243712 (30.75MB)
used = 28918584 (27.57891082763672MB)
free = 3325128 (3.1710891723632812MB)
89.68751488662348% used

 

參考文獻

【1】http://docs.oracle.com/javase/7/docs/api/java/lang/management/ManagementFactory.html

【2】http://blog.csdn.net/xieyuooo/article/details/9817231

【3】http://xstarcd.github.io/wiki/Java/JVM_Heap_Non-heap.html

【4】https://zhidao.baidu.com/question/1989362303218106827.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM