This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Well, I'm not sure why you would NOT want a contiguous region.
The heap is going to be used to store objects of arbitrary size; some of them live for the length of the program, some are garbage after a few seconds. Garbage collection (for a couple of algorithms, anyway) is going to go through all the objects, figure out which ones are still in use, and then make all other space available. With contiguous space, it can collect a number of objects that were allocated in space next to each other, and then use that space for whatever sized objects come up next.
If the heap space is NOT contiguous, then a long-lived object allocated in the middle of a smaller space cuts that space up into smaller, less useful pieces; i.e., if you have 500M of heap space and it is in 1M contiguous blocks, and you allocate a 2K block out of the middle of one of them, then you have two 499K pieces; you cannot use either of them for a 750K object. If you had one contiguous block, you aren't left to deal with as many limits of your contiguous space, and allocation is easier and faster (since you don't have to figure out things about different contiguous spaces).
I believe some JVMs such as JRockit don't have this limitation, which suggests it not specifically required by the JVM specification (although I haven't checked this). The fact that Sun chose to do it this way suggests there are probably advantages related to memory management and garbage collection.
Gaurav Kushwaha wrote:I have a query regarding memory allocation in heap. Why we need contiguous memory region for the heap ?
Do you mean heaps in general or the Java heap? If the first, then the algorithm requires it.
I believe that heapspace was originally configured as a heap; however there's been an awful lot of water under the bridge since their first use, so there may well be more sophisticated structures now.