title: Detecting out of memory errors
body: <p>I would like to provide my system with a way of detecting whether out of memory exception has occurred or not. The aim for this exercise is to expose this flag through JMX and act correspondingly (e.g. by configuring a relevant alert on the monitoring system), as otherwise these errors sit unnoticed for days.</p>
  
  <p>Naive approach for this would be to set an <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.UncaughtExceptionHandler.html">uncaught exception handler</a> for every thread and check whether the raised exception is instance of <code>OutOfMemoryError</code> and set a relevant flag. However, this approach isn't realistic for the following reasons:</p>
  
  <ul>
  <li>The exception can occur anywhere, including 3rd party libraries. There is nothing I can do to prevent them catching <code>Throwable</code> and keeping it for themselves.</li>
  <li>Libraries can spawn their own threads and I have no way of enforcing uncaught exception handlers for these threads.</li>
  </ul>
  
  <p>One of possible scenarios I see is bytecode manipulation (e.g. attaching some sort of aspect on top of <code>OutOfMemoryError</code>), however I am not sure if that's right approach or whether this is doable in general.</p>
  
  <p>We have <code>-XX:+HeapDumpOnOutOfMemoryError</code> enabled, but I don't see this as a solution for this problem as it was designed for something else - and it provides no Java callback when this happens.</p>
  
  <p>Has anyone done this? How would you solve it or suggest solving it? Any ideas are welcome.</p>