Heap memory is a type of memory that is allocated dynamically during the execution of a program. It is also known as "dynamic" memory and is different from local stack memory. Heap memory is a pile of memory space available to programmers to allocate and de-allocate. Every time an object is created, it is always stored in heap space, and the referencing information to these objects is always stored in stack memory. Heap memory is accessible or exists as long as the whole application or program runs.
Heap memory is not as safe as stack memory allocation because the data stored in this space is accessible or visible to all threads. If a programmer does not handle this memory well, a memory leak can happen in the program. The processing time or accessing time of heap memory is quite slow compared to stack memory. Heap memory is also not as thread-safe as stack memory because data stored in heap memory is visible to all threads.
Heap memory provides greater control for the programmer, as the blocks of memory can be requested in any size, and they remain allocated until they are no longer pointed to and recovered by the garbage collector. An object in heap memory can be passed back to the caller of a function, since it is not deallocated when that function exits. The heap memory can be divided into three parts: New or Young Generation, Old or Tenured Generation, and Permanent Generation. The size of heap memory is large when compared to stack memory. The unused objects in the heap memory are cleared automatically by the Garbage Collector in Java.