directory
- 1. The description of the JVM
- 2. Class loading subsystem
- 3. Run time data area
- 4. Vm stack
- 5. The heap area
- 6. Method of area
- 7. Object instantiation and memory access
- Overview of garbage collection
- 9. Classic garbage collector
- 10. The G1 and ZGC
The JVM heap area is used to store objects generated by the Java runtime, and arrays and objects are never stored on the stack, but allocated in the heap. The stack frame holds a reference to an object that points to the starting position of the object or array in the heap.
A JVM instance has only one run-time data area and only one heap memory, which is shared by all threads.
1. An overview of the
1. There is only one heap memory per JVM instance, and the heap is the core area of Java memory management
2. The Java heap area is created at JVM startup and its size is determined. Is the largest chunk of memory managed by the JVM (the size of heap memory is adjustable)
3. The Java Virtual Machine Specification states that a heap can be in a physically discontinuous memory space, but logically it should be treated as continuous.
4. All threads share the Java heap and can also be allocated Thread Local Allocation Buffer (TLAB). No, TLAB threads are unique to the heap.)
5. The Java Virtual Machine Specification describes the Java heap as: all object instances and arrays should be allocated on the heap at run time. From a practical usage point of view, “almost” all instances of objects are allocated memory here (” almost “because they might be stored on the stack, see also escape analysis)
6. Arrays or objects are never stored on the stack because the stack frame holds a reference to the location of the object or array in the heap.
7. Objects in the heap are not removed immediately after the method ends, but only during garbage collection
8. The heap is the area where the Garbage collector (GC) performs Garbage Collection
2. Composition of heap area
2.1 Evolution of heap area
Starting with JDK1.8, permanence is replaced with a meta-space that uses local memory instead of JVM memory
2.2 Composition of heap area
The main components of heap area: Eden area (object birth), Survivor 0 area, survivor 1 area (object survival did not exceed the threshold), old age (object survival exceeds the threshold), permanent generation
2.3 Cenozoic and Old age
1. Java objects stored in the JVM can be divided into two categories: short-lived, transient objects that are created and die very quickly, and objects that are very long-lived and, in some cases, consistent with the JVM’s life cycle
2. The Java heap area can be further divided into YoungGen and OldGen. The young generation can be divided into Eden space, Survivor0 space and Survivor1 space (sometimes also called FRmo zone, to zone).
3. Configure the proportion of Cenozoic and old generation in the heap structure
The default value is -xx :NewRatio= 2, indicating that the Cenozoic era occupies 1, the old age occupies 2, and the Cenozoic era occupies 1/3 of the whole heap. This can be modified. -xx :NewRatio=4, indicating that the Cenozoic era occupies 1, the old age occupies 4, and the Cenozoic era occupies 1/5 of the whole heap
4. In hotSpot, the default ratio between Eden space and two Survivor Spaces is 8:1:1 (6:1:1 at test time), and developers can adjust the ratio with the option -xx :SurvivorRatio, such as ** -xx :SurvivorRatio=8**
5. Almost all Java objects are newly created in Eden
6. Most Java objects are destroyed in the new generation (IBM research indicates that 80% of objects in the new generation are “dead”)
7. You can use the -xmn option to set the maximum memory size for the new generation.
3. Object allocation process
1. The object of new is first placed in Eden Park, which has a size limit
2. When the Eden space fills up, the program needs to create objects again. The JVM’s garbage collector will perform a Minor GC on Eden, destroy objects that are no longer referenced by other objects in Eden, and move the remaining Eden objects to Survivor 0
3. Load new objects and place them in Eden
4. If garbage collection is triggered again, objects that survived the last time will be stored in Survivor 0. If they are not collected, they will be stored in Survivor 1
5. If you go through a garbage collection again, it will be put back into Survivor 0. Then proceed to Survivor one
6 When the number of times of survival in the survivor area reaches the set number, enter the old age area
Setting times: -xx :MaxTenuringThreshold=15
7. In the pension area, it is relatively leisurely. When the memory of the elderly area is insufficient, GC: Major GC is triggered again to clean the memory of the elderly area.
8. If the endowment area still cannot save objects after performing Major GC, an OOM exception will be generated.
3.1 Graphic Process
Summary: For survivor S0,s1: swap after copy, who is empty and who is to. About garbage collection: frequently collected in newborn area, rarely collected in endowment area, almost no longer collected in permanent area/meta-space.
Note: minorGC/youngGC will only be touched when Eden is full, and minorGC will never be triggered when the survivor zone is full. If the survivor area is full, the object is placed directly into the old age. If the adaptive switch is turned on at this time, the size of the new generation will be adjusted after GC ends
Summary: Copy is followed by swap, whoever is empty is to
3.2 Flowchart of Allocating large Objects
4.Minor GC、Major GC、Full GC
JVM GC does not always collect all three memory regions (new generation, old generation, method region), but most of the time the collection refers to the new generation.
In the implementation of hotSpot VM, there are two types of GC in the collection region: Partial GC and Full GC.
1. Partial collection: Garbage collection that does not collect the entire Java heap. Which are divided into:
- Minor GC/Young GC: This is just garbage collection for the new generation
- Major GC (Old GC) : Just Old GC
At present, only the CMS GC has the behavior of collecting old GC separately. In many cases, the Major GC will be confused with the Full GC. Mixed GC is used to distinguish between the old GC and the whole generation GC. Mixed collection does not involve method area recovery, only new generation, old age mixed collection. For now, the LATER G1 GC will have this behavior.
2. Full GC: Collects the entire Java heap and method area garbage collection.
4.1 Trigger mechanism of different GC
1. Triggering mechanism of Minor GC
When a young generation runs out of space, a Minor GC is triggered. When a young generation is full, the Eden generation is full, and a Survivor full does not trigger a GC.(Each Minor GC cleans up the memory of the young generation, Survivor is a passive GC, not an active GC.) So Minor GC is very frequent and generally fast, which is both clear and easy to understand. The Minor GC causes the STW (Stop the World) to suspend other users’ threads until the garbage collection is complete.
2. Major GC/Full GC trigger mechanism
A Major or Full GC occurs when an object disappears from the old age.
The Major GC occurs, often accompanied by at least one Minor GC (not always, the Parallel Scavenge avenge strategy is used directly to select a Major GC).
That is, when the old decade runs out of space, the Minor GC is first attempted. If you are running out of memory after a Major GC is triggered, the Major GC is usually 10 times slower than the Minor GC, and the STW is longer. If you are running out of memory after a Major GC, you will get OOM
3.Full GC triggering mechanism
Full GC execution can be triggered in one of five ways
- 1. When system.gc () is called, Full GC is recommended, but not necessarily executed
- 2. Lack of space in the old era
- 3. Insufficient space in method area
- 4. The average size of the old age after passing the Minor GC is “larger” than the available memory of the old age
- 5. If the object is copied from Eden and Survivor (from) to S1 (to), the object is saved to the old age because the available memory is to Space, and the available memory in the old age is smaller than the object size
Note: Full GC is something to avoid during development or tuning, so that pause times are shorter
4.2 Generation idea of heap space
According to research, the life cycle of different objects is different. 70-99% of objects are temporary objects.
New generation: Eden and Survivor (S0,s1 is also called from to). To is always empty
Old age: Store objects that have survived many times in the new generation
The only reason for generational is to optimize GC performance. If there is no generation, then all the objects are in one place, which is like putting all the people in one school in one classroom. When the GC to find which objects was useless, it will scan all the sections of pile, and many objects are facing life in death, if a generational, put the newly created object in a certain place, when the GC to store the first “in life in death” object area for recycling, this will make a lot of space.
Summary of memory allocation strategy: If an object survives after Eden is born and passes the first Minor GC and can be accommodated by Survivor, it will be moved to Survivor space, setting that to age the object to 1. Each time an object survives MinorGC in a Survivor zone, it increases in age by one year, and when it reaches a certain age (15 by default, which varies from JVM to GC), it is promoted to the old age
The age threshold for the object to be promoted to the old age can be set with the option -xx: MaxTenuringThreshold
The object allocation principles for different age groups are as follows:
- Eden is assigned priority
- Large objects are allocated directly to the old age
- We want to avoid too many large objects in our programs
- Long-lived objects are assigned to the old age
- Dynamic object age determination
- If the sum of the size of all objects of the same age in the Survivor zone is greater than half of the size in the Survivor zone, objects older than or equal to that age can go straight to the old age. There is no need to wait until the age required in MaxTenuringThreshold
4.3 Guarantee mechanism for space allocation
1. Large objects directly enter the old age: 60M heap space is allocated, 20m for the new generation, 16m for Eden, 2m for S0, 2m for S1, 20m for buffer objects. Eden cannot store buffer and is directly promoted to the old age.
2. Large objects in Eden area are directly advanced to the old age: When allocating memory to the large object, the Eden space has almost been allocated. As we have just said, when Eden space is insufficient for allocating memory, the virtual machine will initiate a Minor GC. During THE GC, the virtual machine finds that the large object cannot be saved into Survivor space. So we have to allocate the guarantee mechanism: the new generation objects are moved forward to the old age, where there is enough space to store allocation1, so Full GC does not occur. After a Minor GC, memory is allocated in the Eden region if the later allocated objects can have Eden region.
5.TALB
5.1 Why Does TLAB (Thread Local Allocation Buffer) Exist?
It is well known that the heap is a thread shared area in which any thread can access the shared data. Because object instances are created so frequently in the JVM, it is not thread-safe to partition memory from the heap in a concurrent environment. In order to avoid multiple threads operating on the same address, it is necessary to use mechanisms such as locking, thus affecting the allocation speed. To solve this problem, TLAB came into being.
TLAB allocation process
5.2 What is TLAB
The Eden region continues to be partitioned from the perspective of the memory model rather than garbage collection, and the JVM allocates a private cache region for each thread, which is contained within Eden space
Using TLAB can avoid a series of non-thread-safe problems while improving the throughput of memory allocation. Therefore, we can call this method of allocating memory fast allocation strategy. All JVMS derived from OpenJDK provide TLAB design
5.3 TLAB instructions
Although not all object instances can successfully allocate memory in TLAB, the single JVM explicitly uses TLAB as the preferred memory allocation option. In the program, the developer can use the option -xx :UseTLAB setting to enable TLAB space. By default, TLAB space is very small, occupying only 1% of EDen space. , of course, we can through the options – XX: TLABWasteTargetPercent set the percentage of Eden TLAB space occupies space size, once the object in TLAB space allocated memory fails, the JVM will try to through the use of the locking mechanism to ensure data of atomic operation, Memory is allocated directly in Eden space.
6. Set heap space parameters
-xx :PrintFlagsInitial: Displays the default initial values of all parameters.
-xx :PrintFlagsFinal: View final values of all parameters (subject to change, no longer initial values)
The command to view a specific parameter:
JPS: View the current running process
Jinfo-flag SurvivorRatio process ID: Displays the ratio of Eden Spaces to S0/S1 Spaces in the new generation
-xms: initial heap memory (default: 1/64 of physical memory)
-xmx: maximum heap space memory (default: 1/4 of physical memory)
-xMN: Set the new generation size (initial value and maximum value)
-xx :NewRatio: Configures the proportion of new generation and old generation in the heap structure
-xx :SurvivorRatio: sets the ratio of Eden and S0/S1 Spaces in the new generation
-xx :MaxTenuringThreshold: Set the maximum age of garbage in the new generation (default: 15)
-xx :+PrintGCDetails: displays detailed GC processing logs
To display gc information, run the following command: ① -xx :+PrintGC ② -verbose: GC
– XX: HandlePromotionFailure: whether to set the space allocation guarantee HandlePromotionFailure parameters shows that in the event of a Minor GC, virtual opportunity to check whether the old s largest contiguous space available is greater than the total space of the new generation all objects.
- If it is, the Minor GC is safe
- If less than, the virtual opportunity view – XX: HandlePromotionFailure setting whether to allow guarantees failure.
- If HandlePromotionFailure=true, it continues to check whether the maximum contiguous available space of the old age is greater than the average size of objects promoted to the old age over time.
- If so, we try a Minor GC, just to see if we can trigger the allocation guarantee (we definitely want the allocation guarantee to succeed Eden–>old/ Tentired), but this Minor GC is still risky;
- If less than, a Full GC is performed instead.
- If HandlePromotionFailure=false, do a Full GC instead.
Note: After JDK6 Update24 (JDK7), HandlePromotionFailure does not affect the virtual machine’s space allocation guarantee policy. But it is no longer used in code. The rule after JDK6 Update24 changes to: Minor GC is performed whenever the continuous space of the old generation is larger than the total size of the new generation or the average size of the previous promotions, otherwise Full GC is performed.
7. Escape analysis, stack allocation
With the development of JIT compilers and the maturity of escape analysis techniques, on-stack allocation and scalar replacement make the allocation of some objects not only on the stack
-
If, after escape analysis, an object does not escape the method, then it is optimized to allocate on the stack so that it does not need to allocate on the heap.
-
The basic behavior of escape analysis is the usage space of the analysis object
After jdK6U23, escape analysis is enabled in hotSpot by default
Escape analysis can also be turned on using -xx :+DoEscapeAnalysis as shown
Run -xx :+PrintEscapeAnalysis to view the result of escape analysis
7.1 Escape analysis, code optimization
Stack allocation converts heap allocation to stack allocation. If an object is allocated in a subroutine, the pointer to that object should never escape.
Second, synchronization elision (lock elimination). If an object is found to be accessible only by one thread, operations on that object may be performed without synchronization
Third, separated objects or scalar replacement, some objects may not need to be stored as a continuous memory structure can be accessed, then the object part can not be stored in memory,
Scalar: A common variable
Aggregate quantity: an object composed of multiple variables