如果发生OutOfMemoryError,则Java进程的行为 [英] Behavior of a Java process in case of OutOfMemoryError

查看:105
本文介绍了如果发生OutOfMemoryError,则Java进程的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

获取 OutOfMemoryError .有没有定义好的行为?进程会崩溃还是进入等待/睡眠状态?

What would be the behavior of a Java program on getting OutOfMemoryError. Is there any defined behavior? Will the process crash or would it go into wait/sleep state?

更新::如果我未在代码中对其进行处理?

Update: if I am not handling it in my code?

推荐答案

OutOfMemoryError的处理方式与任何其他异常一样:

And OutOfMemoryError is handled like any other exception:

  • 如果发现它,则什么也不会发生.
  • 如果未捕获,则线程
  • If it is caught, then nothing more happens.
  • If it is not caught, then either the threads or the threads groups uncaught exception handler handles it. This pretty much always leads to the thread being stopped.

但是有两个因素在其他例外情况中并没有真正存在:

However there are two factors that are not really there in other exceptions:

  • OutOfMemoryError Error ,而不是 Exception .这意味着不太可能被捕获到任何地方:您不应该尝试捕获Error的一般情况(例外情况很少),并且通常不会这样做,因此处理它的机会相当大低.
  • 如果发生OutOfMemoryError并且没有任何对象因此而具有资格获得GC的资格,那么您仍然剩余的存储空间将很小,并且有可能再次遇到完全相同的问题以后.
  • OutOfMemoryError is an Error and not an Exception. This means that it's very unlikely to be caught anywhere: You should not try to catch an Error generally (with very few exceptions) and it's not usually done, so the chances of it being handled are rather low.
  • When an OutOfMemoryError happens and no object become eligible for GC because of that, then you'll still have little memory left and chances are that you'll run into the exact same problem again later on.

如果该线程是唯一的非守护进程线程(通常但不一定是那是执行main方法的主线程),则该线程被杀死会导致整个JVM关闭(通常被称为崩溃").

And if the thread this happens to is the only non-daemon thread (often, but not necessarily, that's the main thread, that executes the main method), then that thread getting killed results in the whole JVM shutting down (which is often perceived as "a crash").

因此 tl; dr 是:它将可能杀死线程,并且如果未解决内存问题,则可能会发生越来越多的线程

So the tl;dr is: It will probably kill the thread, and if the memory-issue is not solved, then this can happen to more and more threads.

这篇关于如果发生OutOfMemoryError,则Java进程的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆