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
3 comments
vic
/2008.04.07 00:10
why do not use “-verbose gc” ?
Nick
/2008.04.08 13:03
Does this give you anything that you can’t get from something like JConsole, which is shipped with java 5?
matthew
/2008.04.08 17:51
@vic: We experimented with -verbose gc, but it was information overload.
@Nick: I’ve heard of JConsole, but must admit that I’ve never really used it. Sounds like it’s worth looking into.
We basically just wanted a quick way to diagnose our frequent (at the time) complaints of “the system is slow”. This command allowed us to instantly see if it was a memory problem, or something more sinister.