Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know about OutOfMemory or StackOverflow errors ahead of time

Tags:

java

exception

In Java, is there a way to know that a StackOverflow error or OutOfMemory exception may happen soon?

The OutOfMemory exception might be an easier one to catch, if one is capable of getting memory usage statistics programmatically, and if one knows ahead of time how much memory needs to be used before the OutOfMemory exception is thrown. But are those values knowable?

For the StackOverflow error, is there a way to get recursion depth, and how does one know what value for recursion depth would cause the error to occur?

By knowing ahead of time whether these errors will happen, I feel I can recover the application more gracefully, instead of watching it crash.

like image 852
David Koelle Avatar asked Apr 27 '09 16:04

David Koelle


People also ask

In what situation stack out of memory occurs?

StackOverflowError happens when you execute too many methods one inside another (for example with an infinite recursion), which is limited by the size of the stack. OutOfMemoryError happens when the JVM runs out of space to allocate new objects, which are allocated on the heap.

Can we catch out of memory exception?

It is possible to catch an OutOfMemoryError (It's an Error , not an Exception ), but you should be aware, that there is no way to get a defined behaviour. You may even get another OutOfMemoryError while trying to catch it. So the better way is to create/use memory aware Caches.

How do I stop stack overflow error?

One method to prevent stack overflow is to track the stack pointer with test and measurement methods. Use timer interrupts that periodically check the location of the stack pointer, record the largest value, and watch that it does not grow beyond that value.

What is the cause of stack overflow?

What causes stack overflow? One of the most common causes of a stack overflow is the recursive function, a type of function that repeatedly calls itself in an attempt to carry out specific logic. Each time the function calls itself, it uses up more of the stack memory.


1 Answers

Anticipating Out of Memory Errors

I'm surprised I didn't see this mentioned in the other posts, but you can use ManagementFactory in Java 5/6 to get at a lot of the memory usage information.

Look at the platform mbean server page for more information on detecting low memory conditions in Java. I believe you can setup notifiers to call code when memory usage reaches a certain threshold.

like image 53
Elijah Avatar answered Sep 20 '22 13:09

Elijah