1

Read the below definition in a book (Oracle Certified Associate, Java by M. Reese Richard.):

"As Stack and Heap share the same memory space, if they collide then the program will terminate."

Is it true?

And how does Stack and Heap memory "Collide"?

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126
  • 6
    Switch to a better book. – SLaks Sep 29 '13 at 15:04
  • 2
    Ever heard of [Stack overflow](http://en.wikipedia.org/wiki/Stack_overflow)? – nosid Sep 29 '13 at 15:04
  • Oracle Certified Associate, Java by M. Reese Richard. – Gokul Nath KP Sep 29 '13 at 15:05
  • That may be a very old book, or it may be referring to some embedded system, or it may be describing an historical artifact. Traditionally, a machine had one stack and one heap. The heap grows up and the stack grows down. If the two meet, you've run out of memory. However this isn't applicable to Java and it's not applicable to most modern systems. – pburka Sep 29 '13 at 15:07
  • 3
    The offending paragraph can be found here: http://books.google.com/books?id=6Xid_E3f2BsC&pg=PA41 Although it would be correct for some historical systems, the author seems to suggest that it applies to Java, which is a huge oversimplification at best. – pburka Sep 29 '13 at 15:10
  • 1
    Check out the top answer to this [question](http://stackoverflow.com/questions/214741/what-is-a-stack-overflow-error). I guess it kinda provides a explanation of this 'collision'. – initramfs Sep 29 '13 at 15:13

1 Answers1

0

Java programs are multithreaded, with each thread allocated a separate stack. They therefore do not have a single stack that grows towards the heap, so Java programs themselves can not cause this collision.

If the stacks of the threads are stored at one end of memory, creation of additional threads could cause the total stack space to grow towards the heap.

The JVM itself will have some stack space, which probably does grow towards the heap space, and so in theory could collide. The JVM should be written to avoid deep (and especially infinite) recursion. If it's stack could grow towards the heap (rather than being finite), it should detect that problem and signal it to the program using a VirtualMachineError.

However, JVMs do not allow the heap to grow in an uncontrolled manner, but are configured with a maximum heap space , and have complete control over creation of new stacks for threads. It can therefore completely prevent collision. The only potential collision would be if creation of a new thread stack was impossible. The JVM would signal that condition using a VirtualMachineError (probably an OutOfMemoryError).

Raedwald
  • 46,613
  • 43
  • 151
  • 237