简体   繁体   中英

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.

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.

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));

看看这篇文章https://cruftex.net/2017/03/28/The-6-Memory-Metrics-You-Should-Track-in-Your-Java-Benchmarks.html ,它提到了GarbageCollectionNotificationInfo并且有实现使用JMH (我还没试过)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM