我写了以下简单的程序:
public class Main{
public static void main(String[] args) throws Exception{
new Thread(() -> {
try{
Thread.sleep(10000);
} catch(Exception ignored){ }
throw new OutOfMemoryError("BOOM!");
}).start();
while(true){
System.out.println("Doing some job...");
try{
Thread.sleep(1000);
} catch(Exception ignored){ }
}
}
}
现在我使用选项java -XX:OnOutOfMemoryError="kill -9 %p" Main
运行它,并期望程序收到SIGKILL
引发的错误。但即使在Doing some job...
被抛出后,它也会打印OutOfMemoryError
:
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Exception in thread "Thread-0" java.lang.OutOfMemoryError: BOOM!
at Main.lambda$main$0(Main.java:11)
at java.lang.Thread.run(Thread.java:748)
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
Doing some job...
这有什么问题?
我在java 1.8.0_66
我尝试java -XX:OnOutOfMemoryError='kill -9 %p' Main
和java "-XX:OnOutOfMemoryError=kill -9 %p" Main
,但它仍在继续......
我还尝试检查并执行sudo java -XX:OnOutOfMemoryError="echo 233 > /root/oom" Main
,预期/root/oom
将包含223
,但未创建任何文件。我做错了什么?
答案 0 :(得分:4)
-XX:OnOutOfMemoryError
仅适用于JVM自身抛出的OutOfMemoryErrors。
用户生成的OutOfMemoryErrors与任何其他常规Throwable没有区别,JVM也不会对它们进行特殊处理。