3

我在哪里可以找到一个 MemoryConsumer.java 程序来测试内存消耗?我知道这样的事情已经存在,因为我通过谷歌看到了对这些事情的引用。例如,这个 Oracle 站点引用了“ConsumeHeap.java”,但我不知道在哪里可以找到该源代码。

热点 1.6 选项

有谁知道在哪里可以找到或如何创建这样的东西?

4

4 回答 4

2

I've used this ObjectSizer class to good effect:

http://www.javapractices.com/topic/TopicAction.do?Id=83

It works by creating huge amounts of object instances, as suggested by Tyler.

于 2011-02-04T18:53:15.613 回答
2

您可以简单地创建大量对象实例并将它们保持在范围内。

ArrayList<SomeObject> listOfObjects = new ArrayList<SomeObject>;
for (int i = 0; i < aBigNumber; i++) {
  listOfObjects.add(new SomeObject());
}
于 2011-02-04T18:48:05.463 回答
1

这真的很简单:

public class ConsumeHeap {
    public static void main(String[] args) {
        int[] a = new int[2000000000];
    }
}

这应该会导致在所有 32 位 VM 上立即引发 OutOfMemoryError。以下应该会引发所有当代 VM 的例外情况,因为它需要 16 * 10^18 字节的内存:

public class ConsumeHeap {
    public static void main(String[] args) {
        int[][] a = new int[2000000000][2000000000];
    }
}
于 2011-02-04T20:13:30.847 回答
0

通常,如果该操作具有较长的运行时间或较高的内存消耗,则该操作被认为是广泛的。一个程序的总使用/空闲内存可以通过java.lang.Runtime.getRuntime()在程序中获取;

运行时有几个与内存相关的方法。以下编码示例演示了它的用法。

package test;

import java.util.ArrayList;
import java.util.List;

public class PerformanceTest {
  private static final long MEGABYTE = 1024L * 1024L;

  public static long bytesToMegabytes(long bytes) {
    return bytes / MEGABYTE;
  }

  public static void main(String[] args) {
    // I assume you will know how to create a object Person yourself...
    List<Person> list = new ArrayList<Person>();
    for (int i = 0; i <= 100000; i++) {
      list.add(new Person("Jim", "Knopf"));
    }
    // Get the Java runtime
    Runtime runtime = Runtime.getRuntime();
    // Run the garbage collector
    runtime.gc();
    // Calculate the used memory
    long memory = runtime.totalMemory() - runtime.freeMemory();
    System.out.println("Used memory is bytes: " + memory);
    System.out.println("Used memory is megabytes: "
        + bytesToMegabytes(memory));
  }
} 
于 2013-01-24T13:13:02.440 回答