16

I have a large Java app that uses massive amounts of memory at times and I would like to monitor this at intervals to see if heap or permgen limits are reached or have gotten near to them.

How can I print out the most relevant pieces of mem usage information using java?

2 Answers 2

20

Here's a snippet from a piece of code we have that periodically logs the memory usage of our app:

import java.lang.management.GarbageCollectorMXBean
import java.lang.management.ManagementFactory
import java.lang.management.MemoryPoolMXBean
import java.lang.management.MemoryUsage

log("Heap", ManagementFactory.getMemoryMXBean().getHeapMemoryUsage());
log("NonHeap", ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage());
List<MemoryPoolMXBean> beans = ManagementFactory.getMemoryPoolMXBeans();
for (MemoryPoolMXBean bean: beans) {
    log(bean.getName(), bean.getUsage());
}

for (GarbageCollectorMXBean bean: ManagementFactory.getGarbageCollectorMXBeans()) {
    log(bean.getName(), bean.getCollectionCount(), bean.getCollectionTime());
}
Sign up to request clarification or add additional context in comments.

2 Comments

Likely copy-paste snafu from editing the original source. Fixed! 👍
Could you please add how the method log works or specify if it comes from any library?
1

You can try visualVM, a Java profiler that goes with every JDK. You will find it in the "bin" folder.

1 Comment

I know of VisualVM and have used it for when I am actively debugging a problem as it is happening. But some problems occur during nightly runs which means I need to log them somewhere to process them later. I could of course leave the VisualVM app open for the night, but it is not quite the long-term solution I am looking for, since logs are permanent and accessible by all users on the system and not tied to my computer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.