是否可以使用MBean记录jvm GC活动,cpu使用情况或其他jvm信息?如果是这样,怎么办?

最佳答案

    ClassLoadingMXBean clMxBean = ManagementFactory.getClassLoadingMXBean();

    System.out.println("loadedClassCount:" + clMxBean.getLoadedClassCount());
    System.out.println("totalLoadedClassCount:" + clMxBean.getTotalLoadedClassCount());
    System.out.println("unloadedClassCount:" + clMxBean.getUnloadedClassCount());

    List<GarbageCollectorMXBean> gcMxBeans = ManagementFactory.getGarbageCollectorMXBeans();
    for(GarbageCollectorMXBean gcMxBean : gcMxBeans)
    {
        System.out.println("\ngcMxBean: " + gcMxBean.getName() +
                 ", collection count:" + gcMxBean.getCollectionCount() +
                  ", Collection time:" + gcMxBean.getCollectionTime() +
                ", Memory Pool Names:" + Arrays.deepToString(gcMxBean.getMemoryPoolNames())  );
    }

    OperatingSystemMXBean osMxBean = ManagementFactory.getOperatingSystemMXBean();
    double systemLoadAverageInLast1Minute = osMxBean.getSystemLoadAverage();
    int availableProcessors = osMxBean.getAvailableProcessors();
    System.out.println("\nlast 1 minute load average over all CPUs: " + systemLoadAverageInLast1Minute);
    System.out.println("last 1 minute load average per CPU: " + (systemLoadAverageInLast1Minute/availableProcessors) );

09-27 08:39