As a developer, one should know about the memory allocations that how variables, function calls, execution instructions or object creation does and what goes where in memory. As a Java developer, we should know about the Java Virtual Machine (JVM) internals that how the run-time data areas works so that we have better grip over the common errors like OutOfMemoryError or StackOverflowError and also to improve the app performance. We will learn about the types of run-time memory areas and how they work.
Terms for understanding:
PC Register stores the memory address of JVM instructions currently executed. This is like a pointer to the current instruction in sequence of instructions of a program. As Java supports multi-threading, a PC Register is created every time when a thread is created. Once the thread is finished, The PC Register will also be destroyed. That’s why, its categorized in Per-Thread Area group.
The program counter (PC) is a register that manages the memory address of the instruction to be executed next.
Like PC Register, JVM Stack is also created when a thread is created. That’s why, its also grouped in Per-Thread Area. Each JVM Stack contains multiple block of JVM frames that stores method-specific values that are short-lived. It stores the local primitives and reference variables and follows the LIFO (Last-In-First-Out) principle so the currently executed method is at the top in the stack. When a method is invoked, a stack frame is created and pushed in the stack that stores the information of invoked method. As soon as method finishes execution, the stack frame will be vanished and when a thread is finished, the stack memory will be reclaimed. This memory is thread-safe as each thread has its own stack. Memory size can be managed in two ways, Fixed and Dynamic (expand as per needed).
The total memory allocated to JVM Stack is very less as compared to Heap Memory. It throws java.lang.StackOverflowError when the memory is full. It usually happens on recursive operations.
“Many Java Virtual Machine publishers reduced the default size of a thread’s call stack from 1MB to 256KB.”
Each thread will have the same amount of stack memory size. The default size can be customized by command -Xss
-- A Stack helps to manage the data in the 'Last in First out' method. When the variable
is not used outside the function in any program, the Stack can be used. It allows you to control and handle memory allocation and deallocation.
It helps to automatically clean up the objects.The Java stack size is the size limit of each Java thread in the Java Virtual Machine (JVM) that runs
the monitoring Model Repository Service
default value is 512K.
Use to increase default memory(1MB) for each thread :-Xss3m
Like Stack memory, JVM allocates memory area for native methods also (methods that written other than Java). Its created per-thread. When a native method executes, all thread related data are saved into this area. Native method stack is only available when JVM supports native methods otherwise it is not available. Likewise JVM Stack, it also can be of two types: fixed and dynamic.
-- Native memory is the memory used by the JVM as it runs on the OS. This includes the memory it uses for the Java heap space, so Java heap memory is just a JVM-managed subset of the native memory used by the rest of the JVM and the code you've written to run in the JVM.
Use to control the size of PermGen/Metaspace(java 8) Memory and prevent OutOfMemoryError,default:12 to 20 MB:-XX:PermSize=128m or -XX:MaxMetaspaceSize=128m
Heap area is created at VM (not JVM but OS VM) startup. The JVM allocates Java heap memory from the OS and then manages the heap space for the Java application. Whenever an object is created of classes or arrays. The JVM sub-allocates a contiguous area of the heap memory to store it. Heap area is the primary storage inside JVM for the runtime data and shared to all thread. As the heap memory is shared to all threads, anyone can create into or access from this area. This is where a garbage collection (GC) comes timely and checks for the unused objects and remove them to claiming the memory back and this is one of the best feature in Java.
-- The Java heap is the area of memory used to store objects instantiated by applications running on the JVM. When the JVM is started, heap memory is created and any objects in the heap can be shared between threads as long as the application is running. PermGen is the part of Heap Space
Memory Generations:-- HotSpot VM’s garbage collector uses generational garbage collection. It separates the JVM’s memory into young generation and old generation.
To check default Heap size in windows:cmd> javaw -XX:+PrintFlagsFinal | find "MaxHeapSize"
Use for initial heap size :-Xms512m or -Xms1g
Use for maximum heap size :-Xmx512m or -Xmx1g
Use to enable for G1 Garbase Collection :-XX:+UseG1GC
Use to Sets the number of threads used during parallel phases of the garbage collectors:-XX:ParallelGCThreads=4
Use to print detail garbase collection logs :-XX:+PrintGCDetails
Use to ...:-Xloggc=c/term/gc.log
Use to Sets a target value for desired maximum pause time. The default value is 200 milliseconds:-XX:MaxGCPauseMillis=200
Use to fixing GC Overhead Limit Exceeded Without Increasing Heap Size:-XX:-UseGCOverheadLimit
Use to adds time-stamp information to the garbage collection :-XX:+PrintGCTimeStamps
Use to print OnOutOfMemoryError message:-XX:+HeapDumpOnOutOfMemoryError
Use to set error file path :-XX:HeapDumpPath=D:\heapdump.hrpof com.allclass.hrmEmployee
Use tools for HeapDump analysis :jmap,jhat
Use tools for ThreadDump analysis :jstack
Use tools for performance monitoring :VisualVM,JProfiler,Yourkit
Method area is created at the JVM startup and shared to all threads. It is a logical part of heap area and give controls to JVM implementer to decide not mandated by the specification that means its size can be decided according to requirements. It contains per-class structures and fields like method local data, static fields, method and constructor codes and runtime constant pool OR simply type/class information. It throws OutOfMemoryError if its area is insufficient during runtime. Though its a part of heap, It may or may not be garbage collected.
-- It contains the code actually a compiled code, methods and its data and fields. Runtime constant pool is also a part of Method Area. Memory for it is by default allotted by JVM and can be increased if needed. Runtime Constant pool is per class representation of constant Table.
It is part of every .class file that contains constants needed to run the code of that class. It is created by the compiler and maintained by JVM that resolves the references of the constant pool during runtime.
These constants include literals specified by the programmer and symbolic references generated by compiler. Symbolic references are basically names of classes, methods and fields referenced from the code. These references are used by the JVM to link your code to other classes it depends on.
The above six types can be classified into 2 groups.
PermGen:
Metaspace:Metaspace are the part of native memory
Fisrt run java by running tomcat
Run the following command that return java PID
c:>tasklist | findstr java return 9324
Run the following command
c:>C:\Program Files\Java\jdk1.8.0_202\bin C:\Program Files\Java\jdk1.8.0_202\bin>jps C:\Program Files\Java\jdk1.8.0_202\bin>jps -v return Initial heap size info
Run the following command
C:\Program Files\Java\jdk1.8.0_202\bin>jmap -heap 9324return heap size info
Run the following command
C:\Program Files\Java\jdk1.8.0_202\bin>jstat -gcutil 9324return garbase collection info
Run the following command
c:>java -XX:+PrintFlagsFinal -version return ava all info
Run the following command
c:>java -XX:+PrintFlagsFinal -version | find "MaxMetaspaceSize" return java MaxMetaspaceSize
Run the following command
c:>java -XX:+PrintFlagsFinal -version | find "HeapSize" return java HeapSize
Total : 27663
Today :5
Today Visit Country :