Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - shutting down on Out of Memory Error

I've heard very contradictory things on how to best handle this, and am stuck with the following dilemma:

  • an OOME brings down a thread, but not the whole application
  • and I need to bring down the whole application but can't because the thread doesn't have any memory left

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.

like image 371
djechlin Avatar asked Aug 23 '12 16:08

djechlin


People also ask

How do I fix out of memory issues in Java?

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.

What happens when Java runs out of memory?

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.

Can we catch out of memory error in 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.


1 Answers

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.

like image 169
Tomasz Nurkiewicz Avatar answered Oct 11 '22 17:10

Tomasz Nurkiewicz