// Get current size of heap in bytes
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();
public class CheckHeapSize {
public static void main(String[] args) {
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("heap size: " + formatSize(heapSize));
System.out.println("heap max size: " + formatSize(heapMaxSize));
System.out.println("heap free size: " + 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));
}
}
public class Check {
public static void main(String[] args) {
MemoryMXBean memBean = ManagementFactory.getMemoryMXBean() ;
MemoryUsage heapMemoryUsage = memBean.getHeapMemoryUsage();
System.out.println(heapMemoryUsage.getMax()); // max memory allowed for jvm -Xmx flag (-1 if isn't specified)
System.out.println(heapMemoryUsage.getCommitted()); // given memory to JVM by OS ( may fail to reach getMax, if there isn't more memory)
System.out.println(heapMemoryUsage.getUsed()); // used now by your heap
System.out.println(heapMemoryUsage.getInit()); // -Xms flag
// |------------------ max ------------------------| allowed to be occupied by you from OS (less than xmX due to empty survival space)
// |------------------ committed -------| | now taken from OS
// |------------------ used --| | used by your heap
}
}