views:

46

answers:

2

I am having a java application and spawns lot of threads..and due to out of memory error..it dies if it runs for too much time.. Is there a jvm configuration parameter, that I can set so that it will wait for memory when no memory is available, instead of throwing out of memory error.

A: 

I do not really think that would be feasible to set as a jvm parameter. You should have -Xmx and -Xms set to the appropriate values for the JVM. After that in your code you can check current free memory on the heap using Runtime.freeMemory. If the free memory is too low you can probably make your thread sleep till you got enough memory to process.

CoolBeans
Also, look at the docs for the java.lang.management package, particularly MemoryMXBean. It gives you access to much more detailed information than Runtime.
Mike Baranczak
+3  A: 

Back up a little. If your app is creating so many threads that the JVM runs out of memory, you really need to refactor to use some sort of thread-pooling mechanism. You could catch the out-of-memory exception and see if any threads have freed up resources and then return without handling it but that's a bad code smell to me.

Kelly French
An OutOfMemoryError is considered a non-recoverable error condition. If you catch it, you probably won't be able to do anything about it. And since it can be thrown from anywhere in the code, catching it may not even be possible. See: http://stackoverflow.com/questions/1692230/is-it-possible-to-catch-out-of-memory-exception-in-java
Mike Baranczak