Java获取当前所在进程的PID详解编程语言

Java获取当前所在进程的PID+java获取当前的GC次数。
import java.lang.management.ManagementFactory; 
import java.lang.management.RuntimeMXBean; 
import javax.management.MBeanServer; 
import javax.management.ObjectName; 
/** 
 * 不同平台和版本下,Mbeans名字不一样。本例为win32+jdk 7_b07 
public class MBeanAccess { 
    public static void main(String[] args) throws Exception { 
        //打印GC次数 
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); 
        ObjectName youngMBean = new ObjectName("java.lang:type=GarbageCollector,name=MarkSweepCompact"); 
        ObjectName tenuredMBean = new ObjectName("java.lang:type=GarbageCollector,name=Copy"); 
        System.out.println("YGC:" + mbs.getAttribute(youngMBean, "CollectionCount")); 
        System.out.println("FGC:" + mbs.getAttribute(tenuredMBean, "CollectionCount")); 
        System.gc(); 
        System.out.println("YGC:" + mbs.getAttribute(youngMBean, "CollectionCount")); 
        System.out.println("FGC:" + mbs.getAttribute(tenuredMBean, "CollectionCount")); 
        int pid = getPid();   
        System.out.println("pid: " + pid);   
        //System.in.read(); // block the program so that we can do some probing on it   
    } 
      
    private static int getPid() {  
        //获取进程的PID 
        RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();   
        String name = runtime.getName(); // format: "[email protected]"   
        try {   
            return Integer.parseInt(name.substring(0, name.indexOf('@')));   
        } catch (Exception e) {   
            return -1;   
        }   
    }   
}

原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/10224.html

(0)
上一篇 2021年7月19日
下一篇 2021年7月19日

相关推荐

发表回复

登录后才能评论