JVM監控:JVM監控指標、JVM監控界面實現、Java監控JVM

本文概要:

           1、監控JVM的哪些指標;

           2、一目瞭然的JVM監控的UI界面;

           3、Java代碼獲取JVM監控狀態。

 

1、監控JVM的哪些指標

                javaVersion                                        /** Java版本號 */
                runTime                                                /** 程序運行時間(ms) */
                loadedClassCount                            /** JVM當前加載類數量 */
                unloadedClassCount                        /** JVM已卸載類數量 */
                heapTotal                                            /** 堆內存大小(字節) */
                heapUsed                                            /** 堆內存已使用(字節) */
                heapUsedPercent                                /** 堆內存使用率 */
                nonHeapTotal                                    /** 堆外內存大小(字節) */
                nonHeapUsed                                        /** 堆外內存已使用(字節) */
                nonHeapUsedPercent                        /** 堆外內存使用率 */
                edenTotal                                            /** Eden區大小(字節) */
                edenUsed                                            /** Eden區已使用(字節) */
                edenUsedPercent                                /** Eden區使用率 */
                edenPeakUsedPercent                        /** Eden區使用率峯值(從上次採集統計) */
                survivorTotal                                    /** Survivor區大小(字節) */
                survivorUsed                                    /** Survivor區已使用(字節) */
                survivorUsedPercent                        /** Survivor區已使用率 */
                survivorPeakUsedPercent                /** Survivor區已使用率峯值(從上次採集統計) */
                oldTotal                                            /** 老區大小(字節) */
                oldUsed                                                /** 老區已使用(字節) */
                oldUsedPercent                                /** 老區已使用率峯值 */
                oldPeakUsedPercent                        /** 老區已使用率峯值(從上次採集統計) */
                permTotal                                            /** 永久區大小(字節) */
                permUsed                                            /** 永久區已使用(字節) */
                permUsedPercent                                /** 永久區使用率 */
                permPeakUsedPercent                        /** 永久區使用率峯值(從上次採集統計) */
                codeCacheTotal                                /** CodeCache區大小(字節) */
                codeCacheUsed                                    /** CodeCache區已使用(字節) */
                codeCacheUsedPercent                    /** CodeCache區使用率 */
                codeCachePeakUsedPercent            /** CodeCache區使用率峯值(從上次採集統計) */
                ygcName                                                /** young gc名稱 */
                ygc                                                        /** young gc次數 */
                ygcTime                                                /** young gc總時間 (ms)*/
                fgcName                                                /** full gc名稱 */
                fgc                                                        /** full gc次數 */
                fgcTime                                                /** full gc總時間 (ms)*/
                threadCount                                        /** JVM當前線程數量 */
                threadPeakCount                                /** JVM線程數量峯值 */
                userThreadCount                                /** JVM當前用戶線程數量 */
                deadLockedThreadCount                    /** JVM死鎖線程數量 */

 

2、一目瞭然的JVM監控的UI界面

3、Java代碼獲取JVM監控狀態

    前面有一篇文章是用Python獲取JVM狀態數據的《JVM監控:python腳本JMX獲取JVM狀態》,這裏用Java代碼獲取JVM狀態數據,可以在自己的應用程序裏定時運行獲取JVM狀態數據,測試兼容JDK1.7/1.8。

package com.tjy.util;

import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;

/**
 * 類描述:JVM GC信息工具類
 * 
 **/
public class JVMGCUtils {
	static private GarbageCollectorMXBean youngGC;
    static private GarbageCollectorMXBean fullGC; 

    static{
    	List<GarbageCollectorMXBean> gcMXBeanList = ManagementFactory.getGarbageCollectorMXBeans();        
        for (final GarbageCollectorMXBean gcMXBean : gcMXBeanList) {
			String gcName = gcMXBean.getName();
			if(gcName==null) {
				continue;
			}
			//G1 Old Generation
			//Garbage collection optimized for short pausetimes Old Collector
			//Garbage collection optimized for throughput Old Collector
			//Garbage collection optimized for deterministic pausetimes Old Collector
			//G1 Young Generation
			//Garbage collection optimized for short pausetimes Young Collector
			//Garbage collection optimized for throughput Young Collector
			//Garbage collection optimized for deterministic pausetimes Young Collector
            if (fullGC == null &&
            	(gcName.endsWith("Old Collector")
            	|| "ConcurrentMarkSweep".equals(gcName) 
                || "MarkSweepCompact".equals(gcName) 
                || "PS MarkSweep".equals(gcName))
            ) {
                fullGC = gcMXBean;
            } else if (youngGC == null &&
            		(gcName.endsWith("Young Generation")
            		|| "ParNew".equals(gcName) 
                    || "Copy".equals(gcName) 
                    || "PS Scavenge".equals(gcName)) 
            ) {
                youngGC = gcMXBean;
            }
        }
    }//static

    //YGC名稱
    static public String getYoungGCName() {
        return youngGC == null ? "" : youngGC.getName();
    }
    
    //YGC總次數
    static public long getYoungGCCollectionCount() {
        return youngGC == null ? 0 : youngGC.getCollectionCount();
    }

    //YGC總時間
    static public long getYoungGCCollectionTime() {
        return youngGC == null ? 0 : youngGC.getCollectionTime();
    }

    //FGC名稱
    static public String getFullGCName() {
        return fullGC == null ? "" : fullGC.getName();
    }
    
    //FGC總次數
    static public long getFullGCCollectionCount() {
        return fullGC == null ? 0 : fullGC.getCollectionCount();
    }

    //FGC總次數
    static public long getFullGCCollectionTime() {
        return fullGC == null ? 0 : fullGC.getCollectionTime();
    }
    
    public static void main(String[] args) {
    	List<List<Long>> listRoot = new ArrayList<List<Long>>();
    	for(;;) {
    		System.out.println("=======================================================================");
	        System.out.println("getYoungGCName: " + JVMGCUtils.getYoungGCName());
	        System.out.println("getYoungGCCollectionCount: " + JVMGCUtils.getYoungGCCollectionCount());
	        System.out.println("getYoungGCCollectionTime: " + JVMGCUtils.getYoungGCCollectionTime());
	        System.out.println("getFullGCName: " + JVMGCUtils.getFullGCName());
	        System.out.println("getFullGCCollectionCount: " + JVMGCUtils.getFullGCCollectionCount());
	        System.out.println("getFullGCCollectionTime: " + JVMGCUtils.getFullGCCollectionTime());
	        List<Long> list = new ArrayList<Long>(1000);
	        listRoot.add(list);
	        try {	        	
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
	        if(list.size() > 1) {
	        	list.remove(0);
	        }
	        Runtime.getRuntime().gc();
    	}
    }
}
package com.tjy.util;

import java.lang.management.ClassLoadingMXBean;
import java.lang.management.CompilationMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.Properties;

/**
 * 類描述:JVM信息工具類
 * 
 **/
public class JVMInfoUtils {
    static private RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
    static private ClassLoadingMXBean classLoad = ManagementFactory.getClassLoadingMXBean();
    //可能爲null
    static private CompilationMXBean compilation = ManagementFactory.getCompilationMXBean();
    static private Properties properties = System.getProperties();

	/**
	 * 獲取JVM進程PID
	 * @return
	 */
	public static String getPID() {
		String pid = System.getProperty("pid");
		if (pid == null) {
	        String name = runtime.getName();
	        if(name != null) {
	        	pid = name.split("@")[0]; 
	        	System.setProperty("pid", pid);        	                    	
	        } 	        
		}
		return pid;
	}
	
    /**
     * 獲取JVM規範名稱
     * @return
     */
    static public String getJVMSpecName() {
        return runtime.getSpecName();
    }

    /**
     * 獲取JVM規範運營商
     * @return
     */
    static public String getJVMSpecVendor() {
        return runtime.getSpecVendor();
    }

    /**
     * 獲取JVM規範版本(如:1.7)
     * @return
     */
    static public String getJVMSpecVersion() {
        return runtime.getSpecVersion();
    }

    /**
     * 獲取JVM名稱
     * @return
     */
    static public String getJVMName() {
        return runtime.getVmName();
    }

    /**
     * 獲取Java的運行環境版本(如:1.7.0_67)
     * @return
     */
    static public String getJavaVersion() {
        return getSystemProperty("java.version");
    }
    
    /**
     * 獲取JVM運營商
     * @return
     */
    static public String getJVMVendor() {
        return runtime.getVmVendor();
    }

    /**
     * 獲取JVM實現版本(如:25.102-b14)
     * @return
     */
    static public String getJVMVersion() {
        return runtime.getVmVersion();
    }

    /**
     * 獲取JVM啓動時間
     * @return
     */
    static public long getJVMStartTimeMs() {
        return runtime.getStartTime();
    }

    /**
     * 獲取JVM運行時間
     * @return
     */
    static public long getJVMUpTimeMs() {
        return runtime.getUptime();
    }

    /**
     * 獲取JVM當前加載類總量
     * @return
     */
    static public long getJVMLoadedClassCount() {
        return classLoad.getLoadedClassCount();
    }

    /**
     * 獲取JVM已卸載類總量
     * @return
     */
    static public long getJVMUnLoadedClassCount() {
        return classLoad.getUnloadedClassCount();
    }

    /**
     * 獲取JVM從啓動到現在加載類總量
     * @return
     */
    static public long getJVMTotalLoadedClassCount() {
        return classLoad.getTotalLoadedClassCount();
    }

    /**
     * 獲取JIT編譯器名稱
     * @return
     */
    static public String getJITName() {
        return null == compilation ? "" : compilation.getName();
    }

    /**
     * 獲取JIT總編譯時間
     * @return
     */
    static public long getJITTimeMs() {
        if (null!=compilation && compilation.isCompilationTimeMonitoringSupported()) {
            return compilation.getTotalCompilationTime();
        }
        return -1;
    }

    /**
     * 獲取指定key的屬性值
     * @param key
     * @return
     */
    static public String getSystemProperty(String key) {
        return properties.getProperty(key);
    }

    static public Properties getSystemProperty() {
        return properties;
    }
}
package com.tjy.util;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.util.ArrayList;
import java.util.List;

/**
 * 類描述:JVM內存信息工具類
 * 
 **/
public class JVMMemoryUtils {
    static private MemoryMXBean memoryMXBean;
    static private MemoryPoolMXBean edenSpaceMxBean;
    static private MemoryPoolMXBean survivorSpaceMxBean;
    static private MemoryPoolMXBean oldGenMxBean;
    static private MemoryPoolMXBean permGenMxBean;
    static private MemoryPoolMXBean codeCacheMxBean;
    
	/**
	 * JVM內存區域使用情況。</br>
	 * <pre>
	 * init:初始內存大小(字節)
	 * used:當前使用內存大小(字節)
	 * committed:已經申請分配的內存大小(字節)
	 * max:最大內存大小(字節)
	 * usedPercent:已經申請分配內存與最大內存大小的百分比
	 * </pre>
	 * @author tangjiyu
	 */
	static public class JVMMemoryUsage {
		//初始內存大小(字節)
	    private long init;
	    //當前使用內存大小(字節)
	    private long used;
	    //已經申請分配的內存大小(字節)
	    private long committed;
	    //最大內存大小(字節)
	    private long max;
	    //已經申請分配內存與最大內存大小的百分比
	    private float usedPercent;
	    
	    public JVMMemoryUsage(MemoryUsage memoryUsage) {
	    	this.setMemoryUsage(memoryUsage);
	    	//this(memoryUsage.getInit(), memoryUsage.getUsed(), memoryUsage.getCommitted(), memoryUsage.getMax());
		}
	    
		public JVMMemoryUsage(long init, long used, long committed, long max) {
			super();			
			this.setMemoryUsage(init, used, committed, max);
		}
		
		private void setMemoryUsage(MemoryUsage memoryUsage) {
	    	if(memoryUsage!=null) {
	    		this.setMemoryUsage(memoryUsage.getInit(), memoryUsage.getUsed(), memoryUsage.getCommitted(), memoryUsage.getMax());
	    	} else {
	    		this.setMemoryUsage(0, 0, 0, 0);
	    	}
		}
		
		private void setMemoryUsage(long init, long used, long committed, long max) {
			this.init = init;
			this.used = used;		
			this.committed = committed;		
			this.max = max;
			if(this.used>0 && max>0) {
				this.usedPercent = used * Float.valueOf("1.0") / max;
			} else {
				this.usedPercent = 0;
			}
		}
		
		public long getInit() {
			return init;
		}
		public long getUsed() {
			return used;
		}
		public long getCommitted() {
			return committed;
		}
		public long getMax() {
			return max;
		}
		public float getUsedPercent() {
			return usedPercent;
		}
		
		@Override
		public String toString() {
			StringBuffer buf = new StringBuffer();
		    buf.append("init = " + init + "(" + (init >> 10) + "K) ");
		    buf.append("used = " + used + "(" + (used >> 10) + "K) ");
		    buf.append("committed = " + committed + "(" +
		               (committed >> 10) + "K) " );
		    buf.append("max = " + max + "(" + (max >> 10) + "K)");
		    buf.append("usedPercent = " + usedPercent);
		    return buf.toString();
		}	
	}
	
    static {
        memoryMXBean = ManagementFactory.getMemoryMXBean();
        
        List<MemoryPoolMXBean> memoryPoolMXBeanList = ManagementFactory.getMemoryPoolMXBeans();        
        for (final MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeanList) {
			String poolName = memoryPoolMXBean.getName();
			if(poolName==null) {
				continue;
			}
			// 官方JVM(HotSpot)提供的MemoryPoolMXBean
			// JDK1.7/1.8 Eden區內存池名稱: "Eden Space" 或  "PS Eden Space"、 “G1 Eden Space”(和垃圾收集器有關)
			// JDK1.7/1.8 Survivor區內存池名稱:"Survivor Space" 或 "PS Survivor Space"、“G1 Survivor Space”(和垃圾收集器有關)
			// JDK1.7  老區內存池名稱: "Tenured Gen" 
			// JDK1.8  老區內存池名稱:"Old Gen" 或 "PS Old Gen"、“G1 Old Gen”(和垃圾收集器有關)
			// JDK1.7  方法/永久區內存池名稱: "Perm Gen" 或 "PS Perm Gen"(和垃圾收集器有關)
			// JDK1.8  方法/永久區內存池名稱:"Metaspace"(注意:不在堆內存中)
			// JDK1.7/1.8  CodeCache區內存池名稱: "Code Cache" 
			if (edenSpaceMxBean==null && poolName.endsWith("Eden Space")) {
				edenSpaceMxBean = memoryPoolMXBean;
			} else if (survivorSpaceMxBean==null && poolName.endsWith("Survivor Space")) {
				survivorSpaceMxBean = memoryPoolMXBean;
			} else if (oldGenMxBean==null && (poolName.endsWith("Tenured Gen") || poolName.endsWith("Old Gen"))) {
				oldGenMxBean = memoryPoolMXBean;
			} else if (permGenMxBean==null && (poolName.endsWith("Perm Gen") || poolName.endsWith("Metaspace"))) {
				permGenMxBean = memoryPoolMXBean;
			}  else if (codeCacheMxBean==null && poolName.endsWith("Code Cache")) {
				codeCacheMxBean = memoryPoolMXBean;
			} 
		}
    }// static

	
    /**
     * 獲取堆內存情況
     * @return 不能獲取到返回null
     */
    static public JVMMemoryUsage getHeapMemoryUsage() {
    	if(memoryMXBean!=null) {
    		final MemoryUsage usage =memoryMXBean.getHeapMemoryUsage();
    		if(usage!=null) {
    			return new JVMMemoryUsage(usage);
    		}
    	}
        return null;
    }

    /**
     * 獲取堆外內存情況
     * @return 不能獲取到返回null
     */
    static public JVMMemoryUsage getNonHeapMemoryUsage() {
    	if(memoryMXBean!=null) {
    		final MemoryUsage usage =memoryMXBean.getNonHeapMemoryUsage();
    		if(usage!=null) {
    			return new JVMMemoryUsage(usage);
    		}
    	}
        return null;
    }
    
    /**
     * 獲取Eden區內存情況
     * @return 不能獲取到返回null
     */
    static public JVMMemoryUsage getEdenSpaceMemoryUsage() {
    	return getMemoryPoolUsage(edenSpaceMxBean);
    }
    
    /**
     * 獲取Eden區內存峯值(從啓動或上一次重置開始統計),並重置
     * @return 不能獲取到返回null
     */
    static public JVMMemoryUsage getAndResetEdenSpaceMemoryPeakUsage() {
    	return getAndResetMemoryPoolPeakUsage(edenSpaceMxBean);
    }
     
    /**
     * 獲取Survivor區內存情況
     * @return 不能獲取到返回null
     */
    static public JVMMemoryUsage getSurvivorSpaceMemoryUsage() {
    	return getMemoryPoolUsage(survivorSpaceMxBean);
    }
    
    /**
     * 獲取Survivor區內存峯值(從啓動或上一次重置開始統計),並重置
     * @return 不能獲取到返回null
     */
    static public JVMMemoryUsage getAndResetSurvivorSpaceMemoryPeakUsage() {
    	return getAndResetMemoryPoolPeakUsage(survivorSpaceMxBean);
    }
    
    /**
     * 獲取老區內存情況
     * @return 不能獲取到返回null
     */
    static public JVMMemoryUsage getOldGenMemoryUsage() {
    	return getMemoryPoolUsage(oldGenMxBean);
    }
    
    /**
     * 獲取老區內存峯值(從啓動或上一次重置開始統計),並重置
     * @return 不能獲取到返回null
     */
    static public JVMMemoryUsage getAndResetOldGenMemoryPeakUsage() {
    	return getAndResetMemoryPoolPeakUsage(oldGenMxBean);
    }
    
    /**
     * 獲取永久區/方法區內存情況
     * @return 不能獲取到返回null
     */
    static public JVMMemoryUsage getPermGenMemoryUsage() {
    	return getMemoryPoolUsage(permGenMxBean);
    }

    /**
     * 獲取永久區/方法區內存峯值(從啓動或上一次重置開始統計),並重置
     * @return 不能獲取到返回null
     */
    static public JVMMemoryUsage getAndResetPermGenMemoryPeakUsage() {
    	return getAndResetMemoryPoolPeakUsage(permGenMxBean);
    }
    
    /**
     * 獲取CodeCache區內存情況
     * @return 不能獲取到返回null
     */
    static public JVMMemoryUsage getCodeCacheMemoryUsage() {
    	return getMemoryPoolUsage(codeCacheMxBean);
    }
    
    /**
     * 獲取CodeCache區內存峯值(從啓動或上一次重置開始統計),並重置
     * @return 不能獲取到返回null
     */
    static public JVMMemoryUsage getAndResetCodeCacheMemoryPeakUsage() {
    	return getAndResetMemoryPoolPeakUsage(codeCacheMxBean);
    }
   
    static private JVMMemoryUsage getMemoryPoolUsage(MemoryPoolMXBean memoryPoolMXBean) {
    	if(memoryPoolMXBean!=null) {
			final MemoryUsage usage = memoryPoolMXBean.getUsage();
			if(usage!=null) {
				return new JVMMemoryUsage(usage);
			}
    	}
		return null;
	}
    
    static private JVMMemoryUsage getAndResetMemoryPoolPeakUsage(MemoryPoolMXBean memoryPoolMXBean) {
    	if(memoryPoolMXBean!=null) {
			final MemoryUsage usage = memoryPoolMXBean.getPeakUsage();
			if(usage!=null) {
				memoryPoolMXBean.resetPeakUsage();
				return new JVMMemoryUsage(usage);
			}
    	}
		return null;
	}

    public static void main(String[] args) {
    	List<List<Long>> listRoot = new ArrayList<List<Long>>();
    	for(;;) {
    		System.out.println("=======================================================================");
	        System.out.println("getHeapMemoryUsage: " + JVMMemoryUtils.getHeapMemoryUsage());
	        System.out.println("getNonHeapMemoryUsage: " + JVMMemoryUtils.getNonHeapMemoryUsage());
	        System.out.println("getEdenSpaceMemoryUsage: " + JVMMemoryUtils.getEdenSpaceMemoryUsage());
	        System.out.println("getAndResetEdenSpaceMemoryPeakUsage: " + JVMMemoryUtils.getAndResetEdenSpaceMemoryPeakUsage());
	        System.out.println("getSurvivorSpaceMemoryUsage: " + JVMMemoryUtils.getSurvivorSpaceMemoryUsage());
	        System.out.println("getAndResetSurvivorSpaceMemoryPeakUsage: " + JVMMemoryUtils.getAndResetSurvivorSpaceMemoryPeakUsage());
	        System.out.println("getOldGenMemoryUsage: " + JVMMemoryUtils.getOldGenMemoryUsage());
	        System.out.println("getAndResetOldGenMemoryPeakUsage: " + JVMMemoryUtils.getAndResetOldGenMemoryPeakUsage());
	        System.out.println("getPermGenMemoryUsage: " + JVMMemoryUtils.getPermGenMemoryUsage());
	        System.out.println("getAndResetPermGenMemoryPeakUsage: " + JVMMemoryUtils.getAndResetPermGenMemoryPeakUsage());
	        System.out.println("getCodeCacheMemoryUsage: " + JVMMemoryUtils.getCodeCacheMemoryUsage());
	        System.out.println("getAndResetCodeCacheMemoryPeakUsage: " + JVMMemoryUtils.getAndResetCodeCacheMemoryPeakUsage());
	        List<Long> list = new ArrayList<Long>(10000);
	        listRoot.add(list);
	        try {	        	
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
	        
	        if(list.size() > 1) {
	        	list.remove(0);
	        }
	        Runtime.getRuntime().gc();
    	}
    }
}

 

package com.tjy.util;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

/**
 * 類描述:JVM 線程信息工具類
 * 
 **/
public class JVMThreadUtils {
    static private ThreadMXBean threadMXBean;

    static {
        threadMXBean = ManagementFactory.getThreadMXBean();
    }

    /**
     * Daemon線程總量
     * @return
     */
    static public int getDaemonThreadCount() {
        return threadMXBean.getDaemonThreadCount();
    }

    /**
     * 當前線程總量
     * @return
     */
    static public int getThreadCount() {
        return threadMXBean.getThreadCount();
    }
    
    /**
     * 獲取線程數量峯值(從啓動或resetPeakThreadCount()方法重置開始統計)
     * @return
     */
    static public int getPeakThreadCount() {
        return threadMXBean.getPeakThreadCount();
    }
    
    /**
     * 獲取線程數量峯值(從啓動或resetPeakThreadCount()方法重置開始統計),並重置
     * @return
     * @Throws java.lang.SecurityException - if a security manager exists and the caller does not have ManagementPermission("control").
     */
    static public int getAndResetPeakThreadCount() {
    	int count = threadMXBean.getPeakThreadCount();
    	resetPeakThreadCount();
        return count;
    }
    
    /**
     * 重置線程數量峯值
     * @Throws java.lang.SecurityException - if a security manager exists and the caller does not have ManagementPermission("control").
     */
    static public void resetPeakThreadCount() {
        threadMXBean.resetPeakThreadCount();
    }
    
    /**
     * 死鎖線程總量
     * @return
     * @Throws IllegalStateException 沒有權限或JVM不支持的操作
     */
    static public int getDeadLockedThreadCount() {
        try {
            long[] deadLockedThreadIds = threadMXBean.findDeadlockedThreads();
            if (deadLockedThreadIds == null) {
                return 0;
            }
            return deadLockedThreadIds.length;
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
    
    public static void main(String[] args) {
    	for(;;) {
    		System.out.println("=======================================================================");
	        System.out.println("getDaemonThreadCount: " + JVMThreadUtils.getDaemonThreadCount());
	        System.out.println("getNonHeapMemoryUsage: " + JVMThreadUtils.getThreadCount());
	        System.out.println("getPeakThreadCountAndReset: " + JVMThreadUtils.getAndResetPeakThreadCount());
	        System.out.println("getDeadLockedThreadCount: " + JVMThreadUtils.getDeadLockedThreadCount());
	        try {	        	
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
    	}
    }
}
package com.tjy.task.impl.app;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.tjy.util.JVMGCUtils;
import com.tjy.util.JVMInfoUtils;
import com.tjy.util.JVMMemoryUtils;
import com.tjy.util.JVMMemoryUtils.JVMMemoryUsage;
import com.tjy.util.JVMThreadUtils;

/**
 * 
 * 應用狀態監控,包括應用類型,版本,所在的tomcat名以及數據庫連接等信息(代碼有刪減)
 * 
 * 
 */
public class ApplicationMonitorTask extends AbstractMonitorTask<ApplicationMonitorMessage> {

	@Override
	protected ApplicationMonitorMessage doRun() {
		return this.createMessage();
	}

	private ApplicationMonitorMessage createMessage() {
		ApplicationMonitorMessage message = new ApplicationMonitorMessage();
		// APP
		message.setVersion(ErlangMonitorConfigManager.getConfig().getAppVersion());
		// JVM
		setJVMInfo(message);
		// DB
		setDBInfo(message);
		return message;
	}

	private void setJVMInfo(ApplicationMonitorMessage message) {
		try {
			message.setPid(Integer.parseInt(JVMInfoUtils.getPID()));
		} catch (Exception e) {
		}
		message.setJavaVersion(JVMInfoUtils.getJavaVersion());
		message.setRunTime(JVMInfoUtils.getJVMUpTimeMs());
		message.setLoadedClassCount(JVMInfoUtils.getJVMLoadedClassCount());
		message.setUnloadedClassCount(JVMInfoUtils.getJVMUnLoadedClassCount());
		JVMMemoryUsage heapMemoryUsage = JVMMemoryUtils.getHeapMemoryUsage();
		if (heapMemoryUsage != null) {
			message.setHeapTotal(heapMemoryUsage.getMax());
			message.setHeapUsed(heapMemoryUsage.getUsed());
			message.setHeapUsedPercent(heapMemoryUsage.getUsedPercent());
		}
		JVMMemoryUsage nonHeapMemoryUsage = JVMMemoryUtils.getNonHeapMemoryUsage();
		if (nonHeapMemoryUsage != null) {
			message.setNonHeapTotal(nonHeapMemoryUsage.getMax());
			message.setNonHeapUsed(nonHeapMemoryUsage.getUsed());
			message.setNonHeapUsedPercent(nonHeapMemoryUsage.getUsedPercent());
		}
		JVMMemoryUsage edenMemoryUsage = JVMMemoryUtils.getEdenSpaceMemoryUsage();
		if (edenMemoryUsage != null) {
			message.setEdenTotal(edenMemoryUsage.getMax());
			message.setEdenUsed(edenMemoryUsage.getUsed());
			message.setEdenUsedPercent(edenMemoryUsage.getUsedPercent());
		}
		JVMMemoryUsage edenPeakMemoryUsage = JVMMemoryUtils.getAndResetEdenSpaceMemoryPeakUsage();
		if (edenPeakMemoryUsage != null) {
			message.setEdenPeakUsedPercent(edenPeakMemoryUsage.getUsedPercent());
		}
		JVMMemoryUsage survivorMemoryUsage = JVMMemoryUtils.getSurvivorSpaceMemoryUsage();
		if (survivorMemoryUsage != null) {
			message.setSurvivorTotal(survivorMemoryUsage.getMax());
			message.setSurvivorUsed(survivorMemoryUsage.getUsed());
			message.setSurvivorUsedPercent(survivorMemoryUsage.getUsedPercent());
		}
		JVMMemoryUsage survivorPeakMemoryUsage = JVMMemoryUtils.getAndResetSurvivorSpaceMemoryPeakUsage();
		if (survivorPeakMemoryUsage != null) {
			message.setSurvivorPeakUsedPercent(survivorPeakMemoryUsage.getUsedPercent());
		}
		JVMMemoryUsage oldGenMemoryUsage = JVMMemoryUtils.getOldGenMemoryUsage();
		if (oldGenMemoryUsage != null) {
			message.setOldTotal(oldGenMemoryUsage.getMax());
			message.setOldUsed(oldGenMemoryUsage.getUsed());
			message.setOldUsedPercent(oldGenMemoryUsage.getUsedPercent());
		}
		JVMMemoryUsage oldGenPeakMemoryUsage = JVMMemoryUtils.getAndResetOldGenMemoryPeakUsage();
		if (oldGenPeakMemoryUsage != null) {
			message.setOldPeakUsedPercent(oldGenPeakMemoryUsage.getUsedPercent());
		}
		JVMMemoryUsage permGenMemoryUsage = JVMMemoryUtils.getPermGenMemoryUsage();
		if (permGenMemoryUsage != null) {
			message.setPermTotal(permGenMemoryUsage.getMax());
			message.setPermUsed(permGenMemoryUsage.getUsed());
			message.setPermUsedPercent(permGenMemoryUsage.getUsedPercent());
		}
		JVMMemoryUsage permGenPeakMemoryUsage = JVMMemoryUtils.getAndResetPermGenMemoryPeakUsage();
		if (permGenPeakMemoryUsage != null) {
			message.setPermPeakUsedPercent(permGenPeakMemoryUsage.getUsedPercent());
		}
		JVMMemoryUsage codeCacheGenMemoryUsage = JVMMemoryUtils.getCodeCacheMemoryUsage();
		if (codeCacheGenMemoryUsage != null) {
			message.setCodeCacheTotal(codeCacheGenMemoryUsage.getMax());
			message.setCodeCacheUsed(codeCacheGenMemoryUsage.getUsed());
			message.setCodeCacheUsedPercent(codeCacheGenMemoryUsage.getUsedPercent());
		}
		JVMMemoryUsage codeCacheGenPeakMemoryUsage = JVMMemoryUtils.getAndResetCodeCacheMemoryPeakUsage();
		if (codeCacheGenPeakMemoryUsage != null) {
			message.setCodeCachePeakUsedPercent(codeCacheGenPeakMemoryUsage.getUsedPercent());
		}

		message.setYgcName(JVMGCUtils.getYoungGCName());
		message.setYgc(JVMGCUtils.getYoungGCCollectionCount());
		message.setYgcTime(JVMGCUtils.getYoungGCCollectionTime());
		message.setFgcName(JVMGCUtils.getFullGCName());
		message.setFgc(JVMGCUtils.getFullGCCollectionCount());
		message.setFgcTime(JVMGCUtils.getFullGCCollectionTime());

		message.setThreadCount(JVMThreadUtils.getThreadCount());
		message.setThreadPeakCount(JVMThreadUtils.getAndResetPeakThreadCount());
		message.setUserThreadCount(message.getThreadCount() - JVMThreadUtils.getDaemonThreadCount());
		message.setDeadLockedThreadCount(JVMThreadUtils.getDeadLockedThreadCount());
	}

}

 

【參考文檔】

          《JVM監控》

發佈了57 篇原創文章 · 獲贊 248 · 訪問量 41萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章