# Java memory model - the main concepts

In 
JVM
Published 2022-12-03

This tutorial explains the main concepts of Java memory model.

Here is the simplified image of the Java memory model:

# Java HEAP memory

  • Contains static variables and object variables. These variables could be referenced by the threads variable.
  • Is created when the virtual machine starts up.
  • Contains Young Generation and Old Generation memories.
  • Young Generation is the place where all the new objects are created.
  • Old Generation contains the objects that are long-lived and survived after many rounds of Minor GC.
  • The memory for the heap does not need to be contiguous and could be fixed or variable in size.
  • If Heap space gets full, OutOfMemory error is thrown by JVM.
  • Heap memory is not thread-safe as all objects share it.
  • The String Pool is the place in heap where the String objects are maintained.

# Thread Stack memory

  • Is the memory zone used for the execution of the threads. Each thread has its own thread stack for keeping the local variables (the primitives only) and the methods call stack.
  • The objects are reference type variables. In the Thread Stack we keep the reference to the value stored in the heap.

# Permanent Generation memory (for Java 7 and less )

  • Contains the application metadata required by the JVM to describe the classes and methods used in the application.
  • Permanent Generation memory could be named "Perm Gen" or "Perm".
  • Contains Java library classes and methods.

# Metaspace (for Java 8+)

Metaspace, like the Perm Gen, is the implementation of the Method Area in the JVM specification. However, the key distinction between Metaspace and the Permanent Generation lies in the fact that Metaspace is not within the JVM heap but rather utilizes native memory (outside JVM heap).

# Memory settings

-Xms : For setting the initial HEAP size when JVM starts

-Xmx : For setting the maximum HEAP size.

-Xmn : For setting the size of the Young Generation, rest of the space goes for Old Generation.

-Xss : To define the STACK memory size.

-XX:PermGen : For setting the initial size of the Permanent Generation memory.

-XX:MaxPermGen : For setting the maximum size of Perm Generation memory.