gpt4 book ai didi

java - 如何预测 java.lang.OutOfMemory 异常?

转载 作者:行者123 更新时间:2023-11-30 09:00:14 25 4
gpt4 key购买 nike

是否可以通过编程方式实现?

这是我尝试过的:

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

public class TestMemory {

public static void main(String[] args) {

int kb = 1024;

//Getting the runtime reference from system
Runtime runtime = Runtime.getRuntime();

//Print used memory
System.out.println("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / kb);

//Print free memory
System.out.println("Free Memory:" + runtime.freeMemory() / kb);

//Print total available memory
System.out.println("Total Memory:" + runtime.totalMemory() / kb);

//Print Maximum available memory
System.out.println("Max Memory:" + runtime.maxMemory() / kb);

List<String> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
for (int j = 0; j < 1000; j++) {
list.add("abcdefghij" + i + j);
}
if (i % 1000 == 0) {
try {
Thread.sleep(500);
System.out.println("Free Memory:" + runtime.freeMemory() / kb + " Kb");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}

和输出:

Used Memory:289
Free Memory:15582
Total Memory:15872
Max Memory:126720
Free Memory:15405 Kb
Free Memory:22820 Kb (long pause, longer than 500ms and then exception)
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOfRange(Arrays.java:2694)
at java.lang.String.<init>(String.java:203)
at java.lang.StringBuilder.toString(StringBuilder.java:405)
at TestMemory.main(TestMemory.java:32)

这对我来说意义不大。我希望“可用内存”值在崩溃前减少。如何编写一个循环检查可用内存并在出现此异常之前通知我内存量?

最佳答案

我不认为尝试管理您自己的程序以避免 OutOfMemoryException 是一种好方法。您必须在堆之前调整大小以满足您的内存需求。无论如何对我来说你的代码是正确的但你需要调用 GC:System.gc() 在调用 runtime.freeMemory() 之前。

 if (i % 1000 == 0) {
try {
System.gc();
Thread.sleep(500);
System.out.println("Free Memory:" + runtime.freeMemory() / kb + " Kb");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

关于java - 如何预测 java.lang.OutOfMemory 异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26886261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com