Logging Memory Usage in Java

2008.03.25 08:12

Sometimes 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.

3 comments

why do not use “-verbose gc” ?

Does this give you anything that you can’t get from something like JConsole, which is shipped with java 5?

@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.

Comments? (moderated as hell)

allowed HTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>