I've been getting some OutOfMemory errors lately in my application. Is it possible to detect ahead of time when the virtual machine is running low on memory? In other words to preemptively deal with OutOfMemory errors before they actually occur?

+3  A: 

I suggest that a better question is "Why is my application running out of memory?"

You may need to increase the memory available to the JVM at startup; You may have a memory leak (objects that aren't getting released when they're no longer needed.)

More information on the application might also be helpful

  • Does it run continuously, 24x7x365?
  • Does it run once and exit?

Using performance monitoring/profiling tools to find the cause of the memory problem is really your best bet.

Ken Gentle
+1  A: 

Have a look at the freeMemory method of Runtime (see for details)

In short: do


Notably, that value is only memory consumed in Java. Any memory used by linked native libraries is not counted.
Chris Dolan
+5  A: 

Java (as of Java 5) now has a standard JMX bean that can be used to receive low memory notification. See