How to view the current heap size that an application is using?

后端 未结 7 564
小鲜肉
小鲜肉 2020-11-30 22:03

I think I increased my heap size to 1 GB in NetBeans since I changed the config to look like this:

netbeans_default_options=\"-J-Xmx1g ......
7条回答
  •  渐次进展
    2020-11-30 22:50

    public class CheckHeapSize {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            long heapSize = Runtime.getRuntime().totalMemory(); 
    
            // Get maximum size of heap in bytes. The heap cannot grow beyond this size.// Any attempt will result in an OutOfMemoryException.
            long heapMaxSize = Runtime.getRuntime().maxMemory();
    
             // Get amount of free memory within the heap in bytes. This size will increase // after garbage collection and decrease as new objects are created.
            long heapFreeSize = Runtime.getRuntime().freeMemory(); 
    
            System.out.println("heapsize"+formatSize(heapSize));
            System.out.println("heapmaxsize"+formatSize(heapMaxSize));
            System.out.println("heapFreesize"+formatSize(heapFreeSize));
    
        }
        public static String formatSize(long v) {
            if (v < 1024) return v + " B";
            int z = (63 - Long.numberOfLeadingZeros(v)) / 10;
            return String.format("%.1f %sB", (double)v / (1L << (z*10)), " KMGTPE".charAt(z));
        }
    }
    

提交回复
热议问题