PDA

View Full Version : Java - alert before OutOfMemoryError


Yakisoba
10-24-2006, 06:01 AM
I'm working with a small application that runs multiple threads and potentially can get caught up in a very deep recursive process...

Everything works fine and, obviously, as the recursion gets deeper the execution time is increased...

each time the recursive method is called it sends output to a text area that can be saved at the users request.

Once the program fills the text area with approximately 212000 lines it crashes and gives me a
"java.lang.OutOfMemoryError: Java heap space" error...

Is there a way I can monitor the Heap space being used (in real time) and detect when it reaches a certain point and have things fail a little more gracefully?

Upon "googling" for a solution I came across this page (http://www.javaspecialists.co.za/archive/Issue092.html) which gives an example of a OutOfMemoryError Warning System. This sounds like exactly what I am looking for but I can not get it to work for me...it's not much of a tutorial.

Any suggestions/tutorials would be greatly appreciated.

Thanks,

Yak

Aradon
10-25-2006, 08:51 AM
If you wanted it to fail gracefully I believe you can catch an OutOfMemoryException and do with it as you please.

Although I could be mistaken. Basically it sounds like you're not concerned about the why it happens, as you already know that, but you're more concerned of the after effects.

If you're creating a gui then this issue on that same page may be of interest:

Issue 089 (http://www.javaspecialists.co.za/archive/newsletter.do?issue=089)

Yakisoba
10-25-2006, 10:16 AM
The problem I had with "catching" the OOME is that; once you get that error the application is already broken.
i.e. program freezes, repaint() not called, cannot close window, etc...
(yes, I am creating a GUI)

That said, I was hoping to catch this error, before it occurs, and warn the user of the potential disaster ahead.

Essentially I would like to detect when, lets say 85%, of the heap is in use, then pause the program and tell the user what is (potentially) about to happen. If the user would like to continue they could initiate some "garbage" collection to free up some space in an attempt to allow the program to complete.

Yak