jvm option

By ukmodak | March 31st 2024 10:34:01 AM | viewed 54 times

JVM Option

Java Memory Allocation: Stack vs Heap and other areas:

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:

  • JVM (Java Virtual Machine) is by definition a virtual machine that simulates what a real machine does. It has an instruction set, a virtual computer architecture and an execution model. It is capable of running code written with this virtual instruction set.
  • HotSpot is an implementation of JVM concept or specification. It was originally developed by Sun and now it is owned by Oracle. There are other implementations of the JVM specification, like JRockit, IBM J9, among many [others].

Types of JVM run-time data areas::
  1. Program Counter (PC) Register

    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.

  2. JVM Stack (Stack memory)

    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

  3. Native Method Area

    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

  4. Heap Memory

    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.

    • Young Generation:--It is further divided into two parts: Eden and Survivor. Every object starts its life from Eden space. When GC does his job, it moves alive objects from Eden space to Survivor space and removed the other un-referenced objects.
    • Old Generation:--It also has two parts: Tenured and Permanent (PermGen). GC moves alive objects from Survivor to Tenured area. And the permanent generation contains the metadata of the classes, methods and the VM.
    • Code-Cache (Virtual or reserved)--The HotSpot Java VM also includes a code cache, containing memory that is used for compilation and storage of native code.

    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

  5. Method Area

    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.

  6. Run-time Constant Pool

    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.

  • Per-Thread -- It means the elements or contents are only accessible to the current thread only.
    1. Program Counter (PC) Register
    2. JVM Stack (Stack memory)
    3. Native Method Area
  • Shared-to-all-Thread -- It means anyone can read or write the element or content of this areas.
    1. Heap Memory
    2. Method Area
    3. Run-time Constant Pool

Garbase collection steps:
  • Marking
  • Normal Deletion
  • Deletion + compacting
Garbase Collection Type:
  • Serial GC
  • Parallal GC
  • Parallal Old GC
  • Concurent Mark Sweep
  • G1 GC
PermGen VS Metaspace:

PermGen:

Metaspace:Metaspace are the part of native memory

Five reason for memory leak
  • Heap size insuficient
  • Metaspace size insuficient
  • Native memory/Stack Size/Tread byte insuficient
  • Large array size that cross jvm
  • Out of swap
Missing issues in programming for memory leak
  • Declare reference of object but object not used this reference do not destroy this reference (that cause heap size increase) at the end as as result garbase can not collect this
  • If response is delay(cause database connection is not closed or not seperate large code in small method)
21 java 8 JVM option sor server
  1. -Xmsheap size>[g|m|k]-- ex:-Xms1g []
  2. -Xmxmax heap size>[g|m|k][]
  3. -XX:MaxMetaspaceSizemetaspace>[g|m|k] -- ex:-XX:MaxMetaspaceSize=2g []
  4. -XX:+CMSClassUnloadingEnabled []
  5. -XX:+UseConcMarkSweepGC []
  6. -XX:+CMSParallelRemarkEnabled []
  7. -XX:+UseCMSInitiatingOccupancyOnly []
  8. -XX:CMSInitiatingOccupancyFraction=percent> -- ex:-XX:CMSInitiatingOccupancyFraction=70 []
  9. -XX:+ScavengeBeforeFullGC []
  10. -XX:+CMSScavengeBeforeRemark []
  11. -XX:+CMSClassUnloadingEnabled []
  12. -XX:+ExplicitGCInvokesConcurrentAndUnloadsClasses []
  13. -XX:+PrintGCDateStamps []
  14. -verbose:gc []
  15. -XX:+PrintGCDetails []
  16. -Xloggc:"c:\term\gc.log" []
  17. -XX:+HeapDumpOnOutOfMemoryError[]
  18. -XX:HeapDumpPath=D:\heapdump\heapdump'date'.hrpof []
  19. -Djava.rmi.server.hostname=internal ip>
  20. -Dcom.sun.management.jmxremote.port=port>
  21. VisualVM Tools and VisualGC plug-ins in VisualVM Tools
-XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSInitiatingOccupancyOnly -XX:+ScavengeBeforeFullGC -XX:+CMSScavengeBeforeRemark -XX:+CMSClassUnloadingEnabled -XX:+ExplicitGCInvokesConcurrentAndUnloadsClasses -XX:+PrintGCDateStamps -verbose:gc -XX:+PrintGCDetails -Xloggc:"D:\heapdump\gc.log" -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=D:\heapdump\heapdumps1.hrpof
How to find java PID:

Fisrt run java by running tomcat

Run the following command that return java PID

c:>tasklist | findstr java

return 9324
How to find java Java Initial Heap size:

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
How to find java Java Heap size:

Run the following command

C:\Program Files\Java\jdk1.8.0_202\bin>jmap -heap 9324 
return heap size info
About Barbase collection:
  1. S0 (Survivor Space 0): The percentage of memory used in the first survivor space.
  2. S1 (Survivor Space 1): The percentage of memory used in the second survivor space.
  3. E (Eden Space): The percentage of memory used in the Eden space (where new objects are allocated).
  4. O (Old Generation): The percentage of memory used in the Old Generation (where long-lived objects reside).
  5. M (Metaspace): The percentage of memory used in the Metaspace (where class metadata and other JVM structures are stored).
  6. YGC: The number of Young Generation garbage collections.
  7. YGCT: The time spent on Young Generation garbage collection (in seconds).
  8. FGC: The number of Full Garbage Collections.
  9. FGCT: The time spent on Full Garbage Collection (in seconds).
How to find java Garbase collection status:

Run the following command

C:\Program Files\Java\jdk1.8.0_202\bin>jstat -gcutil 9324 
return garbase collection info
How to find java all info:

Run the following command

c:>java -XX:+PrintFlagsFinal -version
return ava all info
How to find java MaxMetaspaceSize:

Run the following command

c:>java -XX:+PrintFlagsFinal -version | find "MaxMetaspaceSize"
return java MaxMetaspaceSize
How to find java HeapSize:

Run the following command

c:>java -XX:+PrintFlagsFinal -version | find "HeapSize" 
return java HeapSize
bONEandALL
Visitor

Total : 27663

Today :5

Today Visit Country :

  • United States
  • France