Program counter
The address that points to the bytecode instruction being executed by the current thread
The virtual machine stack
Stores data, instructions, and return addresses required by the current running method
The stack frame
- Local variable scale
- The operand stack
- Dynamic link
- To complete the export
Size limit
-Xss
Local method stack
Methods area
- Class information (class loaders are loaded in
Runtime data area
theMethods area
) - constant
- A static variable
- Just-in-time compiled code
The Java heap
- Instance objects (almost all instance objects)
- An array of
Java heap size Parameter Settings - Xmx heap memory Maximum size that can be allocated - Xms heap memory Initial size of memory allocatedCopy the code
The method area and the Java heap are shared by threads, so why not have a separate method area and the Java heap? Considering the characteristics of the data stored in the thread sharing area, class information, constants, static variables, compiled code and other data belong to the high frequency of use, less change and low recovery efficiency, which is difficult; While instance objects and arrays, most of the life cycle is short, frequent creation and destruction; To sum up, thread sharing area adopts the idea of static and static separation, and separates method area and Java heap, which facilitates efficient garbage collection
Before JDK 1.7, the method area was called permanent generation. After JDK 1.8, the method area was called meta-space
A deep understanding of the run-time data area from the ground up
- Allocating memory (initializing the size and memory allocation of the Java stack, Java heap, method area)
- Class loading (class into method area)
- Constants, static variables, etc. (constant declaration, static constants, etc. Enter the method area)
- Virtual Machine stack (Push frame)
- Object creation and memory allocation
What the Java stack does
In the way of stack frame storage method call process, and store the method call process of the basic data type variables and variables referenced by the object, variables out of scope will be automatically releasedCopy the code
The role of Java heap
Heap memory is used to store objects in Java, whether they are member variables, local variables, or class variables, the objects they point to are stored in the heap memoryCopy the code
Thread sharing or thread exclusivity
-
The stack memory belongs to a single thread. Each thread has a stack memory, and the variables stored in it can only be seen in its owning thread. That is, the stack memory can be understood as the private memory of the thread
-
Objects in heap memory are visible to all threads, and objects in heap memory are accessible to all threads
The size
- Stack memory space is much smaller than the heap memory, stack depth is limited, StackOverFlowError can occur
Out of memory
- Stack overflow
- Stack overflow
- Method area overflow
- Native direct memory overflow
Virtual machine optimization techniques
Compiler optimization technique
- Method to reduce virtual machine frame loading and unloading by inlining
Stack optimization techniques
- Data sharing between stack frames
When do classes unload and recycle after they are loaded?
- All instances of the class have been reclaimed
- The classloader that loaded the class has been reclaimed
- The class object of this class is not referenced anywhere, and the methods of this class cannot be accessed through reflection
-xnoClassGC disable class garbage collection parameters are not configured.
Garbage collector
Memory allocation:
Conventional memory model
- New generation (including Eden[8], From[1] and To[1]) : accounts for 1/3 of the heap space
- Old age: 2/3 of heap space
G1 Memory model
The memory is divided into several blocks of equal size, and each or several blocks are marked as the following different areas for object storage
- Eden
Store the newly created object
- Old
Stores objects in memory that live for a long time
- Survior
Store objects that survived the first few GC's
- Humongous
Storing large objects
Why divide the space into Cenozoic era, old age or block? Its purpose is to facilitate garbage recycling and improve the efficiency of garbage recycling
Object Allocation Principles (General objects)
- Objects are allocated in Eden area first
- Space allocation guarantee
- Big object goes straight to the old age
- Long-lived objects enter the old age
- Dynamic object age determination
Almost all objects are allocated in the heap, but not all
There are also objects allocated on the stack (escape analysis)
Objects allocated in the virtual machine stack do not need to be GC, because stack elements are automatically released after completion of execution, so running on the stack is very efficient, which can improve JVM performance (escape analysis)
The condition for escape analysis (when the object is created) is that no method escapes (does not survive outside of the method) no thread escapes (does not survive outside of the thread) and no close escape parameters are set to be allocated on the stack
New An object ↓ Allocated to the stack (Escape analysis) → Yes → Allocated to the stack ↓ No Buffer allocated by the local thread → Yes → Allocated to Eden area in the heap (TLAB) ↓ No Large object → Yes → Allocated to the old age ↓ No Allocated to Eden area in the heapCopy the code
The type of GC
- Minor /Young GC: Reclaims memory space for the new generation
- Major/Old GC: Reclaims Old memory space
- Full GC: Reclaims the entire heap space memory and method area
Generation collection theory
- The vast majority of our subjects are living and dying
(New Generation)
- The harder an object is to recycle after multiple garbage collections
(Old age)
Garbage collection algorithm
Replication algorithm
Advantages: Simple implementation, efficient operation, memory replication, no memory fragmentation Disadvantages: only half of the utilizationCopy the code
Improvement of replication algorithm: According To research and analysis, most (98%) objects of the new generation will be recovered immediately. Therefore, the memory space atmosphere of the new generation can be divided into three parts, namely Eden(accounting for 80% of the new generation), From(also called survival zone 1, accounting for 10% of the new generation), To(survival zone 2, accounting for 20% of the new generation)
When garbage collection occurs, copy viable objects in Eden To From or To. From and To will enable only one area To store the surviving objects at the same time. (In the first garbage collection, all Eden’s viable objects enter From area, and To area is formatted and idle. In the second garbage collection, the Eden and From area live objects are all entered into the To area, and the From area is formatted and idle. When the memory of the From or To area is full, the space allocation guarantee is directly carried out, and all the surviving objects of the new generation are stored To the old age
Mark-sweep algorithm
Features: Execution efficiency is unstable, and memory fragmentation can easily lead to premature GCCopy the code
Suitable for small scale memory reclamation in the old age
Mark-compact algorithm
Features: object movement, reference updates, user thread pauses, no memory fragmentation, low efficiencyCopy the code
Garbage collectors common in JVMS
- Single-threaded garbage collector
- Multithreaded parallel garbage collector
- Multithreaded concurrent garbage collector
The collector | Collect objects and algorithms | Collector type |
---|---|---|
Serial | New generation, replication algorithm | Single thread |
Par New | New generation, replication algorithm | Parallel multithreaded collector |
Parallel Scavenge | New generation, replication algorithm | Parallel multithreaded collector |
Serial Old | In the olden days, tag sorting algorithms | Single thread |
Parallel Old | In the olden days, tag sorting algorithms | Parallel multithreaded collector |
CMS | In the olden days, tag clearing algorithms | Parallel and concurrent collectors |
G1 | Cenozoic and old age, mark finishing + divide whole into parts | Parallel and concurrent collectors |
How the CMS garbage collector works
- Initial flag (need to suspend all user threads, occupy one user thread to perform GC, mark all objects directly related to GC ROOT)
Take a short
- Concurrent markup (the user thread and GC run at the same time, marking all related objects based on the initial markup)
Time consuming
- Re-mark (need to suspend all user threads because new objects may be created during concurrent marking, re-mark)
Take a short
- Concurrent cleanup (user thread and GC running at the same time)
Time consuming
- Reset thread (replace the thread occupied by GC with the user thread)
Advantages: No need to suspend all user threads disadvantages: , sensitive GC will occupy CPU user threads concurrent execution task, if CPU core number < 4, to a greater influence on the user, floating garbage Concurrent cleaning process may produce new garbage can't handle, can only wait for the next GC, memory fragments Because is the tag removal algorithm used by the CMS, so may produce more memory fragments, After the flag is cleared, if there is a lot of debris, it may start again or switch the Serial Old to clean only onceCopy the code
G1 (Garbage First)
- Pursue pause time
- Region area
- Screening of recycling
- Predictable pause
- Copy and tag collation algorithms
Constant pool (existing in method area)
Static constant pool
- literal
- Symbolic reference
- Information about classes and methods
Run-time constant pool
During object creation, symbolic references need to be converted to direct references, which are placed in the runtime constant pool, such as: Person = new Person() The Person is a direct reference to the instantiated Person object, stored in the runtime constant pool with the hash value of the object’s header.
The process of creating an object in a VIRTUAL machine
Class loading
Check the load
Allocate memory
Partition mode
- Pointer to the collision
It is applicable to the situation where the memory space is relatively regular
- The free list
This method applies to the situation where the memory space is scattered and there are many fragments
Pointer collisions are more efficient than hash tables because hash tables require one more visit to the table structure. However, pointer collisions only work when memory is relatively clean, whereas garbage collection is mostly marked cleanup (because it is faster and requires fewer pauses), so the exact method used depends on the memory available at the timeCopy the code
When allocating memory, the JVM uses an algorithm to determine how much memory is currently occupied by the heap and how tidy it is, using pointer collisions if it is tidy, or using the free list if it is not
Concurrency security issues
-
CAS(Compare and sweep) compares switching
Optimistic locking mechanism
-
The TLAB thread allocates the buffer
In Eden area, each thread is assigned a region to store objects, which reduces the collision problem when threads concurrently apply for memory space
Memory space initialization
Set the allocated memory space to an initial value (not an assignment), such as int :0, Boolean :false, String :null, and so on
Set up the
Set the object header
Object initialization
This is when you decide to call the constructor
Object memory layout
- Object head
1 Stores runtime data for the object itself
2 Type Pointer
The Class to which the object belongsCopy the code
3 If it is an array of objects, it also records the data of the array length
- The instance data
- Alignment filling
The JVM specification states that objects should occupy multiples of 8 bytes, both for addressing (memory address lookup) and for efficient JVM execution (less synchronization and caching).
Object access location
- Use the handle
Divide an area of heap space as a handle pool
The advantage of Pointers to objects is that when the address of the object instance data changes (after GC collation), the reference does not need to change, only the overhead of changing the address of the object to which the pointer pointsCopy the code
- Direct Pointers
Reference to the memory address of the object When the address of the object instance data changes, you need to locate and update the address of the referenceCopy the code
Determines the survival of the object
- Reference counting method
A direct, simple, fast, undiscriminating GC root unreachable circular referenceCopy the code
- Accessibility analysis (root accessibility)
Accurate, efficient and slower than reference countingCopy the code
Mainstream virtual machines use root-reachable algorithms
To determine whether an object should be recycled, we first judge whether the object should be recycled according to the reachability analysis algorithm, and then we judge whether the object has other references (self-salvation of finalize method). Finally, we can judge whether the object should be recycled
Finalize() method When an object is destroyed, the Finalize() method may be called and will only be triggered once at most
Why is it possible?
Because the finalize() method is called ina special Finalize thread, which has a low priority, there is no guarantee that it will be executed immediately before object destruction
All kinds of reference
- Strong reference
- Soft references
SoftReference
Objects held by soft references are not necessarily recycled during garbage collection. Objects held by soft references are only recycled if there is not enough heap space (about OOM)Copy the code
- A weak reference
WeakReference
Only survive until the next garbage collection whenever garbage collection occurs, objects held by weak references must be reclaimedCopy the code
- Phantom reference
PhantomRefrence
The ready collection is primarily used within the JVM to monitor whether the garbage collector is working properlyCopy the code