如果java进程发生OOM, 代码是否可以catch住这个异常?
答案是可以的. 测试代码如下:
public class TestOOM{
public static void main(String[] args) throws Exception{
int ten_mb = 1024 * 1024 * 10;
int count = 10;
new Thread(){
public void run(){
int count = 10;
while(count -- > 0){
System.out.println("i'm running");
try{
Thread.sleep(100);
}catch(Throwable e){
}
}
}
}.start();
while(count -- > 0){
try{
byte[] content = new byte[ten_mb];
}catch(Throwable e){
e.printStackTrace();
}finally{
System.out.println("count down: " + count);
Thread.sleep(1000);
}
}
}
}
使用
java -Xms8m TestOOM
运行程序结果如下:
HaitaoYao-MacPro:tmp haitao$ java -Xmx10m TestOOM
i'm runningjava.lang.OutOfMemoryError: Java heap space
at TestOOM.main(TestOOM.java:24)
count down: 9
i'm running
java.lang.OutOfMemoryError: Java heap space
at TestOOM.main(TestOOM.java:24)
count down: 8
i'm running
java.lang.OutOfMemoryError: Java heap space
at TestOOM.main(TestOOM.java:24)
count down: 7
i'm running
java.lang.OutOfMemoryError: Java heap space
at TestOOM.main(TestOOM.java:24)
count down: 6
i'm running
java.lang.OutOfMemoryError: Java heap space
count down: 5
i'm running
java.lang.OutOfMemoryError: Java heap space
count down: 4
i'm running
java.lang.OutOfMemoryError: Java heap space
count down: 3
i'm running
java.lang.OutOfMemoryError: Java heap space
count down: 2
i'm running
i'm running
java.lang.OutOfMemoryError: Java heap space
count down: 1
java.lang.OutOfMemoryError: Java heap space
count down: 0
可以得出的结论是:
- OutOfMemoryError 可以被catch住, 使用catch Error或者直接catch Throwable
- 其他的线程,如果不在极限情况下分配内存, 仍然可以继续运行.
- catch Throwable 的使用要小心
--EOF--