Java 进程在 OutOfMemoryError 情况下的行为
Java 程序在获取 OutOfMemoryError< 时的行为是什么/a>.有什么明确的行为吗?进程会崩溃还是会进入等待/睡眠状态?
更新:如果我没有在代码中处理它?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
OutOfMemoryError
的处理方式与任何其他异常一样:但是有两个因素在其他异常中并不存在:
OutOfMemoryError
是一个Error
而不是异常
。这意味着它极不可能在任何地方被捕获:一般情况下(除了极少数例外)您不应该尝试捕获错误
,而且通常不会这样做,因此它的处理量相当低。OutOfMemoryError
且没有对象因此有资格进行 GC 时,您仍然只剩下很少的内存,并且很可能会遇到完全相同的情况稍后又出现问题。如果发生这种情况的线程是唯一的非守护线程(通常但不一定是执行
main
方法的主线程),那么该线程被杀死会导致整个 JVM关闭(通常被视为“崩溃”)。所以tl;dr是:它可能会杀死线程,如果内存问题没有解决,那么这种情况可能会发生在越来越多的线程上。
And
OutOfMemoryError
is handled like any other exception:However there are two factors that are not really there in other exceptions:
OutOfMemoryError
is anError
and not anException
. This means that it's very unlikely to be caught anywhere: You should not try to catch anError
generally (with very few exceptions) and it's not usually done, so the chances of it being handled are rather low.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.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").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发生时,你无法确定程序的状态。如果您没有捕获 Throwable,那么您的程序将因堆栈跟踪而终止。即使您捕获了 Throwable,您也应该调用 System.exit,因为从中恢复是没有意义的。 “错误”通常由 JVM 抛出,与特定于应用程序/程序员的异常相反。
You can't determine the state of program when OutOfMemoryError occurs. If you are not catching Throwable then your program will terminate with the stacktrace. Even if you are catching Throwable, you should call System.exit since there is no point in recovering from it. "Error" is generally thrown by JVM, as oppose to Exception, which is application/programmer specific.
OutOfMemoryError 应被视为不可恢复,并且引发此类错误后 JVM 的行为是未定义的,因此没有必要花费精力来处理它。 JVM 抛出此异常后执行的任何操作都将具有未定义的行为。它们可能会执行,但更有可能的是它们只会导致抛出另一个错误。
OutOfMemoryError should be considered unrecoverable and the behavior of the JVM after such an error has been raised is undefined, so there is no point in expending effort to handle it. Any operations done after this exception is thrown by the JVM will have undefined behavior. They may execute, but more likely they will just cause another error to be thrown.