JDK-6201872 : Add a hook mechanism to OutOfMemoryError
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 6
  • Priority: P4
  • Status: Closed
  • Resolution: Won't Fix
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2004-11-30
  • Updated: 2012-01-11
  • Resolved: 2004-12-01
Related Reports
Relates :  
Description
A DESCRIPTION OF THE REQUEST :
I would like to see a hook mechanism added to OutOfMemoryError so that code can be written that would be executed in the event that the VM throws the error.

A possible implementation would be to add some static methods to the OutOfMemoryError object:
OutOfMemoryError.addHook(Runnable hook);
OutOfMemoryError.removeHook(Runnable hook);

A typical, basic use would then be OutOfMemoryError.addHook(new Runnable() { public void run() { System.exit(-1) }});

A VM implementing this RFE would run these hooks just before throwing the error.  Developers implementing the hooks should be responsible for not attempting to create any new objects for which memory may not be available.

JUSTIFICATION :
Most applications enter an unpredictable state when they run out of memory and OutOfMemoryError is thrown.  In my experience, application frameworks do not allow the error to be caught in a simple or consistent fashion.

Typical workarounds I have seen tend to be designed around having a background, daemon thread that regularly calls Runtime.freeMemory() and, depending on settings, calls Runtime.gc() and/or System.exit();

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
Applications can behave predictably in low memory conditions.
ACTUAL -
Applications behave unpredictably in low memory conditions.


Comments
EVALUATION The supported API to monitor the JVM may be found in the package java.lang.management. Specifically, you should consult the specification of MemoryMXBean which describes how to receive memory usage notifications. ###@###.### 2004-12-01 02:25:47 GMT I just saw another similar request that's being addressed by the serviceability team: 6204527: Need mechanism to run user-defined script/command when OutOfMemoryError is thrown ###@###.### 2004-12-13 22:03:56 GMT
01-12-2004