You can do it by MXBeans
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
}
}
But remember it is equivalent to Runtime.getRuntime()
(took depicted schema from here)
memoryMxBean.getHeapMemoryUsage().getUsed() <=> runtime.totalMemory() - runtime.freeMemory()
memoryMxBean.getHeapMemoryUsage().getCommitted() <=> runtime.totalMemory()
memoryMxBean.getHeapMemoryUsage().getMax() <=> runtime.maxMemory()
from javaDoc
init - represents the initial amount of memory (in bytes) that the Java virtual machine requests from the operating system for memory management during startup. The Java virtual machine may request additional memory from the operating system and may also release memory to the system over time. The value of init may be undefined.
used - represents the amount of memory currently used (in bytes).
committed - represents the amount of memory (in bytes) that is guaranteed to be available for use by the Java virtual machine. The amount of committed memory may change over time (increase or decrease). The Java virtual machine may release memory to the system and committed could be less than init. committed will always be greater than or equal to used.
max - represents the maximum amount of memory (in bytes) that can be used for memory management. Its value may be undefined. The maximum amount of memory may change over time if defined. The amount of used and committed memory will always be less than or equal to max if max is defined. A memory allocation may fail if it attempts to increase the used memory such that used > committed even if used <= max would still be true (for example, when the system is low on virtual memory).
+----------------------------------------------+
+//////////////// | +
+//////////////// | +
+----------------------------------------------+
|--------|
init
|---------------|
used
|---------------------------|
committed
|----------------------------------------------|
max
As additional note, maxMemory is less than -Xmx because there is necessity at least in one empty survival space, which can't be used for heap allocation.
also it is worth to to take a look at here and especially here