Pinch
Pinch

Reputation: 2888

How to measure peak heap memory usage in Java?

How to measure peak heap memory usage in Java? MemoryPoolMXBean keeps track of the peak usage per memory pool, but not the entire heap. And the peak heap usage is not simply the sum of different heap memory pools.

Upvotes: 6

Views: 3469

Answers (3)

Alex P.
Alex P.

Reputation: 3787

Look at this article https://cruftex.net/2017/03/28/The-6-Memory-Metrics-You-Should-Track-in-Your-Java-Benchmarks.html, it mentions GarbageCollectionNotificationInfo and there is implementation using JMH (I haven't tried it yet)

Upvotes: 0

beat
beat

Reputation: 2022

If you need the peak heap size, you can combine the peak used size of all the memory pools which are of type HEAP.

Here is an example:

List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
long total = 0;
for (MemoryPoolMXBean memoryPoolMXBean : pools)
{
  if (memoryPoolMXBean.getType() == MemoryType.HEAP)
  {
    long peakUsed = memoryPoolMXBean.getPeakUsage().getUsed();
    System.out.println("Peak used for: " + memoryPoolMXBean.getName() + " is: " + peakUsed);
    total = total + peakUsed;
  }
}

System.out.println("Total heap peak used: " + Util.format(total));

Upvotes: 1

m.aibin
m.aibin

Reputation: 3593

Did you think about using totalMemory() function from Runtime class - docs? Also there are some free tools like VisualVM or JStat, example:

jstat -gc <pid> <time> <amount>

Hope that helps.

Upvotes: 3

Related Questions