简体   繁体   English

到目前为止,如何在没有探查器的情况下在JVM中分配总内存?

[英]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. 我想使用java.lang.management API获取分配给Java程序中某点之前的总内存。 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? 是否有使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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