Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically increasing java heap space

I have written a java program that tests the speed of a couple of multi-threading algorithms on different machines with various numbers of processors.

On some machines, merge sort* fails because it requires a sizable heap space to work on very large arrays. I can easily change the java heap space myself before running the program, but I feel like a more robust and easy approach would be to do this task from within the program itself.

Is there a way to request/achieve more heap space from the virtual machine during the course of a java program?

Note: I do understand that I could execute the program with a script like "java -Xmx1g Program"; my curiosity on this subject is in part academic.

*My implementation does NOT merge in-line. It requires O(n) extra memory.

like image 669
Robz Avatar asked Aug 04 '10 18:08

Robz


People also ask

Is Java heap size dynamic?

Heap space is used for the dynamic memory allocation of Java objects and classes at runtime. New objects are always created in the heap space, and references to these objects are stored in the stack memory.

How increase JVM heap size permanently?

Edit the -Xmx256m option. This option sets the JVM heap size. Set the -Xmx256m option to a higher value, such as Xmx1024m. Save the new setting.

Is there dynamic memory allocation in Java?

Dynamic memory allocation in Java: Dynamic memory allocation in Java means that memory is allocated to Java objects during the run time or the execution time. It is contrary to static memory allocation. The dynamic memory allocation takes place in the heap space.


2 Answers

As far as I know, there is no way of controlling the heap size at runtime.

It may not be necessary though: you can provide a minimum and maximum heap size with the -Xms and -Xmx switches respectively. (eg -Xms128m -Xmx512m) The jvm will manage the actual heap size within these bounds.

like image 75
jvdneste Avatar answered Oct 06 '22 01:10

jvdneste


Java was not design to be able to dynamically manage memory, in this case "java heap space", all the opposite, it was designed in order to relieve the programmer from having to worry about that.

In short, I'm afraid to say that there is nothing like a "malloc()"or "setHeapSize(int byes)" in Java.

On Java you're constraint to the amout of memory available to the JVM when your program starts. In terms of memory management this is both a blessing and a curse.

For that kind of dynamic memory allocation you should try to use implement your algorithm using a language like C and/or C++ instead.

like image 37
Jose Diaz Avatar answered Oct 05 '22 23:10

Jose Diaz