Question

In Java the virtual machine pre-allocates a memory heap which cannot be expanded at runtime. The developer can increase the size of the heap with the -Xmx switch when the VM loads, but there is no way to increase the maximum size of the heap at runtime. Why is this?

Was it helpful?

Solution 2

There is no reason per the JVM specification why the heap size must be specified ahead of time except that it was the choice of the implementors. The specification states: "A Java Virtual Machine implementation may provide the programmer or the user control over the initial size of the heap, as well as, if the heap can be dynamically expanded or contracted, control over the maximum and minimum heap size."

The other answers here are just wrong: "The heap may be of a fixed size or may be expanded as required by the computation and may be contracted if a larger heap becomes unnecessary."

Source: The Java Virtual Machine Specification, Java SE 7 Edition. Section 2.5.3, "Heap." That's page 13 in the printed edition.

OTHER TIPS

Fragmentation is a massive problem in memory allocation, as is memory starvation. It's a lot simpler, and less error-prone if you can allocate and reserve the memory you need, especially in a server environment. By pre-allocating memory, you also have a higher probability of having most of your memory in continuously allocation (not guaranteed, thank you @mttdbrd) which could be faster to access.

Going back to when Java first started out, installations with more than 1GB of RAM were pretty much unheard of, instead, we had to work with machines that had as little as 256mb of RAM, sometimes even less! Couple that with how slow RAM was, and it made much more sense to be able to read and write to hopefully contiguously allocated blocks. You are also not constantly hammering the OS to give you more RAM and then releasing it again, freeing up (back then) precious CPU cycles.

In that environment, it's very easy to run out of memory suddenly, so it made a lot of sense to be able to allocate what you MIGHT need and make sure you would have it when the time comes.

These days, I guess with RAM being so much more accessible, it makes a lot less sense, although, when I look at my servers and how memory is allocated, I love the fact that all my Java applications have nice, mostly contiguously allocated blocks of memory when compared to some of the other applications that are all over the place.

That is also why you can't up the heap at runtime, there's no way to guarantee that you will have a contiguous allocation any more.

When your code starts to work, JVM is already created and configured. Besides, this limitation guarantees that program will not take all available system resources, breaking normal functioning of other applications on a server regardless how bad its code is. ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top