Paste some program code
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryPoolMXBean;
public class MemoryDemo {
static String mb(long s) {
return String.format("%d (%.2f M)", s, (double) s / (1024 * 1024));
}
public static void main(String[] args) {
System.out.println("Runtime max: " + mb(Runtime.getRuntime().maxMemory()));
MemoryMXBean m = ManagementFactory.getMemoryMXBean();
System.out.println("Non-heap: " + mb(m.getNonHeapMemoryUsage().getMax()));
System.out.println("Heap: " + mb(m.getHeapMemoryUsage().getMax()));
for (MemoryPoolMXBean mp : ManagementFactory.getMemoryPoolMXBeans()) {
System.out.println("Pool: " + mp.getName() + " (type " + mp.getType() + ")" + " = " + mb(mp.getUsage().getMax()));
}
}
}
When the program is running, its maximum heap memory is set
-Xmx10m -Xms10m
program output
Runtime max: 10092544 (9.63 M)
Non-heap: 136314880 (130.00 M)
Heap: 10092544 (9.63 M)
Pool: Code Cache (type Non-heap memory) = 50331648 (48.00 M)
Pool: PS Eden Space (type Heap memory) = 2686976 (2.56 M)
Pool: PS Survivor Space (type Heap memory) = 393216 (0.38 M)
Pool: PS Old Gen (type Heap memory) = 7012352 (6.69 M)
Pool: PS Perm Gen (type Non-heap memory) = 85983232 (82.00 M)
The problem is that the memory obtained through Runtime.getRunTime.maxMemory is smaller than the set 10m memory, only 9.63M? as follows. Why?
Runtime max: 10092544 (9.63 M)
In fact, the reason is very simple. maxMemory is the maximum memory that can be used by the obtained program. We know that there are two Survivors, but only one will be used, and the other has been idle. So this value maxMemory is the value of removing a Survivor space.
which is
maxMemory=Eden+Survivor+Old Gen
9.63 M=2.56 M+0.38 M+6.69 M
The above article is referenced from:
The article is the author's original article, if it is helpful to you, welcome to reward!