我需要你的一些专家的理解
该程序不会捕获块(因为堆已满,但我想了解原因)
public class OOME_NotCatch {
static List l = new ArrayList();
static Long i = new Long(1);
public static void main(String[] args) {
try {
while (true) {
l.add(i);
i++;
}
} catch (OutOfMemoryError e) {
e.printStackTrace();
System.out.println("Encountered OutOfMemoryError");
}
}
}
//Console : Exception in thread "main"
但是即使获得了OOME,以下程序仍可以很好地运行:
public class Catch_OOME_Collection {
static List l = new ArrayList();
public static void main(String[] args) {
try {
while (true) {
l.add(new byte[1000000]);
System.out.println("size " + l.size());
}
} catch (OutOfMemoryError e) {
System.out.println("Encountered OutOfMemoryError");
e.printStackTrace();
System.out.println("size of list is " + l.size());
Iterator i = l.iterator();
while(i.hasNext()){
System.out.println(i.next().toString());
i.remove();
}
while (true) {
System.out.println("keep printing");
}
}
}
}
在看到相同错误OOME的不同结果后,我有些困惑。请指导
我的理解是,在第一个程序中,尝试分配新的Long对象(仅占用几个字节的内存)时,将引发OOME。这意味着堆已完全充满,并且不再有可用内存来运行catch块。
在第二个程序中,尝试分配100万字节的新数组时,将引发OOME。它失败了,但这可能意味着堆仍然有999,990字节可用,足以让catch块执行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句