java获取JVM对象实例的个数和占用空间大小

            RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
            String name = bean.getName();
            int index = name.indexOf('@');
            String pid = name.substring(0, index);
            //这里要区分操作系统
            HotSpotVirtualMachine machine = (HotSpotVirtualMachine) new            sun.tools.attach.WindowsAttachProvider().attachVirtualMachine(pid);
            InputStream is = machine.heapHisto("-all");

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int readed;
            byte[] buff = new byte[1024];
            while((readed = is.read(buff)) > 0)
                baos.write(buff, 0, readed);
            is.close();

            machine.detach();
            System.out.println(baos);

输出:

 num     #instances         #bytes  class name
----------------------------------------------
   1:         19474        2107032  [C
   2:           524        2080784  [I
   3:          7500        1026288  
   4:          7500         924248  
   5:           564         624576  
   6:          1581         441592  [B
   7:           564         403464  
   8:           504         394880  
   9:         10176         244224  java.lang.String
  10:          3500          84000  java.lang.StringBuilder
  11:           635          77456  java.lang.Class

你可能感兴趣的:(JAVA,java)