title: How to detect when the Java heap is nearly full and prevent "OutOfMemoryError: Java Heap"?
body: <p>There a quite a few questions in SO related to the "OutOfMemoryError: Java Heap" error, but reading over them, most seem to discuss how to increase the heap size or profiling the app and detecting memory leaks.  </p>
  
  <p>I'm working on a project, that invovles analyzing the cost of a branch and bound algorithm.  For input small input sizes, the potential number of solutions to search grows at O(n!).  At a certain input size, n, I've encountered the "OutOfMemoryError" because the parial solutions are kept in a priority queue until ready to be treated, and the huge number of partial solutions in the queue fills up the memory.  So, I know I don't have a memory leak, and I don't necessarily want to increase the heap size.  </p>
  
  <p>What I'd like to do is simply detect when the memory is nearly full, then give the user a message that tells them what's going on and why the program is exiting (it's not necessary the program keep functioning at this point).  Is there a way to do this?  I have looked at the <code>java.lang.management</code> package, but it doesn't make much sense to me, and I've had difficulty finding decent example code.  Any explanation or example code is appreciated.  </p>