Core Java for Interviews

Stack and Heap

Stack

Stack Memory in Java is used for static memory allocation and the execution of a thread. It contains:

  1. Primitive values that are specific to a method
  2. References to objects referred from the method that are in a heap.

Stack has preallocated size, with the default being 1 MB in most modern operating systems and architectures. This can be customised with -Xss tuning flag. Once the stack size is exhausted, the JVM will throw StackOverFlowError.

-Xss1m 
-Xss1024k

Stack access is performed in LIFO order. After the execution of a function, the stack frame is flushed and the flow goes back to the calling method. Memory space is automatically reclaimed.

Heap

Heap space is used for the dynamic memory allocation of Java objects and JRE classes at runtime. New objects are always created in heap space. These objects can be accessed from anywhere, any threads, in the application.

Heap in Java are divided into three parts, called generation:

  1. Young generation. This is where all new objects are allocated and aged. A minor Garbage collection occurs when this fills up. This is further divided into two portions:
    1. Eden space: when we create an object, the memory will be allocated from the Eden Space.
    2. Survivor space: this contains the objects that have survived from the Young garbage collection or Minor garbage collection. We have two equally divided survivor spaces called S0 and S1.
  2. Old or tenured generation. This is where long surviving objects are stored. When objects are stored in the Young Generation, a threshold for the object’s age is set, and when that threshold is reached, the object is moved to the old generation.
  3. Permanent generation. This consists of JVM metadata for the runtime classes and application methods.

When the heap space is full, Java throws OutOfMemoryError. Memory space is reclaimed by Garbage Collection. Tuning heap space can be done with several JVM flags:

Garbage Collection

PECS

Multithreading

References