Suppose there is a large Java application and I would like to gracefully shut it down if OutOfMemory
error occurs. Now I see the following problems:
- Some components catch and "swallow" all
Throwables
includingOutOfMemory
- If a thread does not catch
OutOfMemory
it exits and we do not know thatOutOfMemory
occurred
Can I somehow register a "JVM-level" handler to catch any OutOfMemory
, which may occur in the JVM?
-
1Be careful that, as specified by Sun, you should not try to do things like saving the state, as "An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.". Those errors are mainly to be used during development, not in production.Denys Séguret– Denys Séguret2012年08月14日 08:07:03 +00:00Commented Aug 14, 2012 at 8:07
-
1graceful and OOM don't work together as OOM can happen anywhere in any thread, monitoring the memory and reaching some level is the only way to do it anywhere gracefully.bestsss– bestsss2012年08月15日 08:02:47 +00:00Commented Aug 15, 2012 at 8:02
3 Answers 3
Some components catch and "swallow" all Throwables including OutOfMemory
They shouldn't do that, I would fix them.
If a thread does not catch OutOfMemory it exits and we do not know that OutOfMemory occurred
That I would fix as well.
You can register an UncaughtExceptionHandler.
The only option might be to trigger a script on an OOME which shuts down you program. This can be done from the command line.
Comments
Out of memory problem is error which means that you can not restore correct JVM state from it and so you can not do any finalization. Instead you can try to monitor your application memory consumption and try to shutdown it correctly if free memory level will be too low (I suppose that this is what you want).
1 Comment
Never catch an error! So, RTFM! ;)
Errors are very strange, so they should throw up to the main and will stop the VM.
Exceptions are throwables, wich can "handled" (SocketTimeoutException, NullpointerException etc.). Errors are throwables that can't handled (in the most common cases). What you wanna do, if an OutOfMemoryError was thrown? Can you extend your memory @ execution time? The garbage collector normally runs multiple times before the OOME will thrown.
So in your special case: Be happy, that you have enough memory to create the OutOufMemoryError-Object to see, what the reason of the VM-Death is.
Refactor your code! ;)