Java内存测试-如何消耗计算机上的所有内存(RAM)

╰半橙微兮° 2023-10-05 16:10 83阅读 0赞

如下是Java 内存消耗程序的源代码。其目的是消耗PC上的所有内存(RAM)。它尝试分配1 MB的字节数组,直到用完RAM。

  1. import java.util.Vector;
  2. public class MemoryEater {
  3. public static void main(String[] args) {
  4. Vector v = new Vector();
  5. int i = 0;
  6. while (true) {
  7. byte b[] = new byte[1048576];
  8. v.add(b);
  9. i = i + 1;
  10. Runtime rt = Runtime.getRuntime();
  11. System.out.println("Total Memory = " +
  12. rt.totalMemory() +
  13. " Free Memory = " +
  14. rt.freeMemory() +
  15. " Allocated Memory = " +
  16. i +
  17. "MB");
  18. }
  19. }
  20. }

使用选项(如下所示)运行此Java 内存消耗程序也很重要,-Xmx以确保您的JVM获得了您希望它拥有的所有内存

$ java -Xmx1024M MemoryEater

上面显示的示例将尝试消耗多达1,024 MB RAM(1 GB)。

当我多次开始显示Windows蓝屏死机时,我编写了与此类似的程序。我发现发生了某种类型的硬件故障,因此我向RAM中写入了很多内容,然后将其读回以查看是否可以通过这种方式找到问题。

IBM J9 JDK 1.4.2 32bit On AIX 64 bit测试结果:

# /usr/java14/bin/java -Xmx6910m MemoryEater
Total Memory = 2950756864 Free Memory = 2948381040
Total Memory = 2950756864 Free Memory = 2947332448

Total Memory = 2950756864 Free Memory = 1073272
JVMDG217: Dump Handler is Processing OutOfMemory - Please Wait.
JVMDG315: JVM Requesting Heap dump file
JVMDG318: Heap dump file written to //heapdump18743486.1608351347.phd
JVMDG303: JVM Requesting Java core file
JVMDG304: Java core file written to //javacore18743486.1608351348.txt
JVMDG274: Dump Handler has Processed OutOfMemory.
JVMST109: Insufficient space in Javaheap to satisfy allocation request
Exception in thread “main” java.lang.OutOfMemoryError
at MemoryEater.main(MemoryEater.java(Compiled Code))

2950756864/1024/1024=2814.061035MB

发表评论

表情:
评论列表 (有 0 条评论,83人围观)

还没有评论,来说两句吧...

相关阅读