0

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.

Boolean
  • 14,266
  • 30
  • 88
  • 129
  • 1
    What I think you need to do is look at an Executors.newFixedThreadPool of an approprate size and limit your threads according to their estimated memory consumption. – Yishai Aug 09 '10 at 17:58

2 Answers2

3

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 S. French
  • 12,198
  • 10
  • 63
  • 93
  • 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 Aug 09 '10 at 19:01
0

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
  • 20,654
  • 10
  • 86
  • 101
  • 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 Aug 09 '10 at 19:13