I have a java program that performs 5 different tasks. When I run the program with -Xmx512m memory parameter, tasks 1-4 run fine but task 5 goes out of memory. When I run the program with -Xmx1024m, all 5 tasks runs fine but tasks 1-4 that previously ran fine with 512m heap now uses up almost all of 1024m heap. The same thing happens if I use -Xms128m -Xmx1024m.
What would be the memory parameters to instruct JVM to keep the memory utilization low (e.g. 512m for tasks 1-4) and only to use more memory when actually needed (e.g. in case of task 5)?
Maybe I need a way to activate the garbage collector more frequently than the default setting?
I think you have a misunderstanding on how the JVM works. This is not a GC issue or a “task” issue.
Your tasks have memory leaks or they are designed to hold onto more and more memory.
-Xmx1024m sets the maximum memory the JVM can allocate. It’d be the same thing as if you only have 1024 megs of physical memory and no virtual memory.
It would be helpful to update your question with the definition of Task. Are these 5 separate JVM’s? Or just 5 units of work in a single JVM.
Update
Just because you set -Xmx1024m does not mean the JVM WILL use all that memory. It’s just a max limit. Setting Xms till set a minimum amount of memory to be used. Your program ultimately determines the running amount of memory being utilized. If it hits the limit set by -Xmx then it will throw an OutOfMemoryError
You can suggest to the JVM to run the Garbage Collector by invoking
System.gc(). Notice I said suggest, you cannot force the GC to run. You could be running on a platform that refuses to even do GC. You also need to look into what GC algorithm it is choosing for your application. I would look here Tuning Garbage Collector.If you need such fine grain controls over memory usage you will need to pick something else besides the JVM.