Java process behavior in case of OutOfMemoryError

What will be the behavior of a Java program when it receives an OutOfMemoryError . Is there any specific behavior? Process failure or transition to standby / sleep state?

Update: if I do not process it in my code?

+6
source share
3 answers

And OutOfMemoryError handled like any other exception:

  • If he is caught, then nothing else happens.
  • If it is not caught, it either processes threads or groups of topics , an exception handler for exception handlers. This almost always causes the thread to stop.

However, there are two factors that do not actually exist in the other exceptions:

  • OutOfMemoryError - Error , not Exception . This means that it can hardly be caught anywhere: you should not try to catch Error in general (with very few exceptions), and this is usually not done, so the chances of handling it are pretty low.
  • When an OutOfMemoryError occurs, and because of this the object cannot access the GC, you will still have a little memory, and most likely you will encounter the same problem again later.

And if the thread to which this happens is the only non-daemon thread (often, but not necessarily, the main thread that executes the main method), then this thread, which kills, terminates the entire JVM (which is often perceived as " crash" ).

So tl; dr : it will probably kill the thread, and if the memory problem is not resolved, this can happen with a lot of threads.

+12
source

You cannot determine the state of a program when an OutOfMemoryError occurs. If you do not catch Throwable, your program will exit using stacktrace. Even if you catch Throwable, you should call System.exit, since there is no point in restoring it. The "error" is usually caused by the JVM, as against Exception, which is specific to the application / programmer.

+1
source

OutOfMemoryError should be considered unrecoverable, and the behavior of the JVM after such an error was raised undefined, so it makes no sense to make efforts to eliminate it. Any operations performed after this exception are generated by the JVM with undefined behavior. They may be executed, but most likely they will simply cause another error.

+1
source

Source: https://habr.com/ru/post/898348/


All Articles