I have developed a stand alone application in java, but its using 70 % of Memory usage of RAM, which makes the system hang. Is there a solution to reduce the memory usage of the java application. Please help.
-
Use less memory by not filling the data structures unnecessarily. – Juned Ahsan Oct 02 '13 at 16:34
-
5CPU or RAM? what are you trying to reduce? – logoff Oct 02 '13 at 16:36
-
We could give you generic solutions, but that will likely cause the program to crash or hang. You need to show us code (however, this might not conform to [so] guidelines, I'm not sure). – Bernhard Barker Oct 02 '13 at 16:49
-
yes, you should write another application, which consumes less :) – VladL Oct 02 '13 at 17:01
-
Thanks a lot I would Try this out. – Shekhar Rana Oct 04 '13 at 10:07
3 Answers
There are numerous GC flags you can use to specify allocations around the JVM, but in all honesty the best optimization for java comes from optimizing your code first.
As for which flags to look into:
-Xmx1024M:
sets the jvm maximum heap size to 1024 megabytes. You can change the amount of RAM allocated to your process.
-XX:+AgressiveOpts
a jvm super-option. This activates other jvm flags. To explain them all would take a lot of time, but basically it enabled optimization and increases cache size. I believe there is an old post on it somewhere... aha: Old Post
You can simply restrict the use of JVM memory settings jdk, or perform a refactoring of your application code, trying to reduce the memory allocation, e.g. reuse instances of objects, using Singleton, between other methods of refactoring

- 167
- 6
Make sure you cleanup your resource, setting variableName = null;
once you don't need it anymore. This will make it better candidate for garbage collection.
You can also cal the garbage collector manually using System.gc();
But the garbage collection is normally done automatically. Calling it manually consume lots of resource and should be the last option.
Another possible memory leak issue: if you concatenate Strings
. Use best StringBuilder
if you need to concatenate strings.
Note: you can monitor the memory usage using untime methods.
Tmp tmp=new Tmp();
Runtime runtime = Runtime.getRuntime();
int procs = runtime.availableProcessors();
String max = tmp.adjust(runtime.maxMemory());
String total = tmp.adjust(runtime.totalMemory());
String used = tmp.adjust(runtime.totalMemory() - runtime.freeMemory());
String free = tmp.adjust(runtime.freeMemory());

- 4,571
- 4
- 40
- 52
-
1Manual calls to the garbage collector is a very bad practice. Edit: See here: [Why explicit garbage collection is bad](http://stackoverflow.com/questions/2414105/why-is-it-a-bad-practice-to-call-system-gc). – Rogue Oct 02 '13 at 16:40
-
I agreee. Calling the garbage collector consume a lot of resource and should not be the first solution. – Cedric Simon Oct 02 '13 at 16:43
-
I would try this, and get back to you. Thanks a lot for the suggestion. – Shekhar Rana Oct 04 '13 at 10:09