I've heard very contradictory things on how to best handle this, and am stuck with the following dilemma:
I've always understood best practice is let them go so the JVM can die because the JVM is in an inconsistent state at that point, but that doesn't seem to be working here.
1) An easy way to solve OutOfMemoryError in java is to increase the maximum heap size by using JVM options "-Xmx512M", this will immediately solve your OutOfMemoryError.
A java. lang. OutOfMemoryError is a runtime error in Java which occurs when the Java Virtual Machine (JVM) is unable to allocate an object due to insufficient space in the Java heap. The Java Garbage Collector (GC) cannot free up the space required for a new object, which causes a java.
Java has the option to catch exceptions and handle them gracefully. For example, you can catch the FileNotFoundException that can be thrown when trying to work with a file that doesn't exist. The same can be done with the OutOfMemoryError – you can catch it, but it doesn't make much sense, at least in most cases.
OutOfMemoryError
is just like any other error. If it escapes from Thread.run()
it will cause thread to die. Nothing more. Also, when a thread dies, it is no longer a GC root, thus all references kept only by this thread are eligible for garbage collection. This means JVM is very likely to recover from OOME.
If you want to kill your JVM no matter what because you suspect it can be in an inconsistent state, add this to your java
options:
-XX:OnOutOfMemoryError="kill -9 %p"
%p
is the current Java process PID placeholder. The rest is self-explained.
Of course you can also try catching OutOfMemoryError
and handling it somehow. But that's tricky.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With