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.
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.
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 java.lang.management 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.
That’s difficult. Mostly because free memory is not really known before a garbage collection takes place, and a serious garbage collection usually only happens just before you run out.
What you can do is explain why the program has crashed after the fact: Eclipse does this for example. You can catch the OutOfMemoryError just like any other Throwable, and show your message: