0

I checked with following code in my servlet:

int mb = 1024 * 1024;
Runtime runtime = Runtime.getRuntime();
out.write("Used Memory:" + (runtime.totalMemory() - runtime.freeMemory()) / mb);
out.write("Free Memory:" + runtime.freeMemory() / mb);
out.write("Total Memory:" + runtime.totalMemory() / mb);
out.write("Max Memory:" + runtime.maxMemory() / mb);

the output is :

Used Memory:10
Free Memory:46
Total Memory:57
Max Memory:57

I want my app not to use more than 64 MB heap? I want to know - is there any way my app can use more then 64 MB heap...(Max Memory:57) ? ..will my app throw an OutOfMemoryException after 57MB?

trincot
  • 317,000
  • 35
  • 244
  • 286
JAVAGeek
  • 2,674
  • 8
  • 32
  • 52
  • If you need more, can't you just define more in the JVM with -Xmx256m for example? – TecHunter Aug 13 '12 at 12:50
  • then just add this parameter to your JVM ( when you launch your tomcat server for example ). You have no way to programatically do this from inside the JVM. – TecHunter Aug 13 '12 at 13:01
  • No.. i want to limit the use of heap memory.and that is why i set -Xmx64m .. ..even if i set max to 64mb.. is that ensured that my app will not use more then 64MB – JAVAGeek Aug 13 '12 at 13:06
  • then you will get a OOM Exception. – TecHunter Aug 13 '12 at 13:07

2 Answers2

1

Default Max Heap size is 64Mo, the only way to get more is to set the max size with this parameter :

-Xmx256m

While this parameter set the start value :

-Xms128m

Don't forget the "m" at the end which means Megabytes, don't give more start memory than max neither. Furthermore, there is no setMaxHeapSize() function if it's what you are looking for.

If you are runnning your servlet inside a tomcat you should try with this :

export CATALINA_OPTS=-Xms16m -Xmx256m;

in startup.bat

If your servlet need more than JVM can allow, you will get weird errors when reaching the limit and most of the time a OutOfMemoryException, the Garbage Collector will try to avoid that though so it will crawl a bit before throwing it.

TecHunter
  • 6,091
  • 2
  • 30
  • 47
0

When you run your application you must also specify the max heap size.

For example if your class name is HelloWorld and if you want to set 512mb the heap size then you have to launch te following command:

java -Xmx512m HelloWorld
Valerio Emanuele
  • 909
  • 13
  • 27