简体   繁体   中英

How to get total memory allocated so far in JVM without profiler?

I want to get the total memory allocated up until some point in a Java program using the java.lang.management API. So far this is what I have:

ManagementFactory.getMemoryPoolMXBeans()
        .stream()
        .map(MemoryPoolMXBean::getPeakUsage)
        .filter(usage -> usage != null)
        .mapToLong(MemoryUsage::getUsed)
        .sum();

I was wondering whether this code will do what I want, or if the results will be misleading and/or incorrect.

You will have the accurate result about the current memory usage by this code.

Here is the sample code for your reference :



    long heapSize = Runtime.getRuntime().totalMemory();
    long max = Runtime.getRuntime().maxMemory();

    StringBuilder message = new StringBuilder();

    message.append("Heap Size = ").append(formatSize(heapSize)).append("\n");
    message.append("Max Heap Size = ").append(formatSize(max)).append("\n");

    for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
      String name = pool.getName();
      MemoryType type = pool.getType();
      MemoryUsage usage = pool.getUsage();
      MemoryUsage peak = pool.getPeakUsage();
      message.append("Heap named '").append(name);
      message.append("' (").append(type.toString()).append(") ");
      message.append("uses ").append(usage.getUsed());
      message.append(" of ").append(usage.getMax());
      message.append(". The max memory used so far is ");
      message.append(peak.getUsed()).append(".\n");
    }
    System.out.println(message.toString());

Hope this will help you.

Why dont you use "Runtime" to get allocated memory,example please check below code below? Is there any specific reason to use java.lang.management?

    Runtime rt = Runtime.getRuntime();
    long totalMemory = rt.totalMemory();
    long freeMemory = rt.freeMemory();
    long usedMemory = totalMemory - freeMemory;

Edit: Below code gives you several stats related to memory

public static void main(String[] args)
 {
   Iterator beans = ManagementFactory.getMemoryPoolMXBeans().iterator();
   while (beans.hasNext())
   {
  MemoryPoolMXBean bean = (MemoryPoolMXBean) beans.next();
  System.out.println("Bean: " + bean);
  System.out.println("Name: " + bean.getName());
  System.out.println("Collection usage: " + bean.getCollectionUsage());
  boolean collectionUsage = bean.isCollectionUsageThresholdSupported();
  System.out.println("Collection usage threshold supported: "
                     + collectionUsage);
  if (collectionUsage)
    {
      System.out.println("Collection usage threshold: "
                         + bean.getCollectionUsageThreshold());
      System.out.println("Setting collection usage threshold to 1MB ("
                         + MB + " bytes)");
      bean.setCollectionUsageThreshold(MB);
      System.out.println("Collection usage threshold: "
                         + bean.getCollectionUsageThreshold());
      System.out.println("Collection usage threshold count: "
                         + bean.getCollectionUsageThresholdCount());
      System.out.println("Collection usage threshold exceeded: "
                         + (bean.isCollectionUsageThresholdExceeded()
                            ? "yes" : "no"));
    }
     System.out.println("Memory manager names: "
                     + Arrays.toString(bean.getMemoryManagerNames()));
  System.out.println("Peak usage: " + bean.getPeakUsage());
  System.out.println("Current usage: " + bean.getUsage());
  System.out.println("Resetting peak usage...");
  bean.resetPeakUsage();
  System.out.println("Peak usage: " + bean.getPeakUsage());
  System.out.println("Current usage: " + bean.getUsage());
  boolean usage = bean.isUsageThresholdSupported();
  System.out.println("Usage threshold supported: " + usage);
  if (usage)
    {
      System.out.println("Usage threshold: "
                         + bean.getUsageThreshold());
      System.out.println("Setting usage threshold to 1MB ("
                         + MB + " bytes)");
      bean.setUsageThreshold(MB);
      System.out.println("Usage threshold: "
                         + bean.getUsageThreshold());
      System.out.println("Usage threshold count: "
                         + bean.getUsageThresholdCount());
      System.out.println("Usage threshold exceeded: "
                         + (bean.isUsageThresholdExceeded()
                            ? "yes" : "no"));
    }
  System.out.println("Valid: " + (bean.isValid() ? "yes" : "no"));
  }
  }
long allocatedMemory = Runtime.getRuntime().maxMemory() - Runtime.getRuntime().freeMemory();

有关更多详细信息,请参见链接: https : //docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html

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