Logging Memory Usage in Java
2008.03.25 08:12Sometimes our system gets slow, and we want to investigate what’s going on. Checking the memory usage is one of the first steps in this process.
I wrote this command to help. It uses the following classes from java.lang.management: ManagementFactory, MemoryMXBean, and MemoryUsage.
@Command(path = CMD_PREFIX + "/memory")
public void mbeanMemory(CommandInvocation ci) {
final MemoryMXBean memoryBean =
ManagementFactory.getMemoryMXBean();
final String date =
new SimpleDateFormat("yyyy/MM/dd hh:mm:ss")
.format(new Date());
ci.out.println(String.format("[%s] heap:{%s}, non-heap:{%s}",
date,
describe(memoryBean.getHeapMemoryUsage()),
describe(memoryBean.getNonHeapMemoryUsage())));
}
private static final String describe(MemoryUsage memory) {
final long max = memory.getMax();
final long used = memory.getUsed();
final long free = max - used;
return String.format("used:%sMB, free:%sMB, max:%sMB",
bytesToMegs(used), bytesToMegs(free), bytesToMegs(max));
}
private static final long bytesToMegs(long bytes) {
return bytes / (1024 * 1024);
}
The @Command annotation is a part of an OSGi Commands system created by one of my colleagues.
category: code