当前位置:网站首页>Different JVM

Different JVM

2022-06-24 18:23:00 Autumn rain——

Preface : Reading needs a certain foundation , Not suitable for the first time JVM The crowd . Some languages are concise , There are some knowledge points or a stroke of knowledge , I don't know that I need to consult the information in detail , The purpose of this article is to supplement JVM Some details , Something a little deeper , Some easily overlooked places , I believe that reading this article will make you feel different from reading eight part essay in the past . More knowledge will be added later . Because the knowledge in this article helps to supplement the knowledge , In some places, if you write in detail , It may take a lot of space , So I selected several links , Their articles are all good , I have seen it , Eat with ease . It is suitable for the people who will be interviewed .( This article does not record the very conventional eight - Part )

Memory area

Pile up

  • Methods for allocating objects on the heap : Pointer collisions and free lists .

Pointer collision requires pointer movement when the heap memory is regular , Memory needed to move ( It depends on whether the garbage collector has compression ).

The free list records memory usage .

The methods to solve the concurrency problem are :CAS, Failure to retry ;TLAB( Allocate a block of memory for each thread , Not enough to apply , Use your own )

  • How to access objects on the heap : Handles and direct pointers .

    Handle :Java The heap divides a chunk of memory into handle pools ,reference The handle address of the object is stored in , The handle contains the specific address of the object instance data and type information .

    Direct Pointers :reference The address of the object is stored in .

    The former is stable , When the address of an object changes ,reference The address of the handle pointed to does not need to be changed .

    The latter is more efficient , One less addressing time .( at present HotSpot The virtual machine uses this )

Method area

Used to store class information loaded by virtual machine 、 Constant 、 static const 、 Real time compiler compiled code 、 Data such as runtime constant pools .

  • Runtime constant pool 、 Constant pool 、 String constant pool (jdk1.8 after , Put the string constant pool in the heap ) The difference between :

    Constant pool :

    java File is compiled into class file ,class The file contains only the version of the class 、 Field 、 Method 、 Interface and other description information , And then there's the constant pool , It is used to store various literal and symbol references generated by the compiler .

 Insert picture description here

 Insert picture description here

Runtime constant pool :

JVM When executing a class , Must be loaded 、 Connect 、 initialization , And connection includes verification 、 Get ready 、 Analyze three stages . When the class is loaded into memory ,JVM Will be class The contents of the constant pool are stored in the runtime constant pool ` in , The runtime constant pool is one for each class . It is then converted to a direct reference at parsing and runtime .

String constant pool : Generate string object instances in the heap after the preparation phase , Then the reference value of the string object instance is stored in the string constant pool .

The reference values are stored in the string constant pool , Instead of specific instance objects , Specific instance objects are stored in a piece of space opened in the heap .

Virtual machine stack

OutOfMemoryError: If the virtual machine stack can be expanded dynamically , When expanding, we can't apply enough memory .

StackOverflowError: The stack depth of the thread request is greater than the virtual machine allows .

Local method stack and program counter

JVM Call local method ( Provide interfaces for other languages ); Program counter : The only one that doesn't have OutOfMemoryError The memory area of the situation .

Out of heap memory

Through a store in Java Heap DirectByteBuffer Object operates as a reference to this memory , To avoid the Java Heaps and Native Copying data back and forth between the heaps .

Permanent generation and meta space

  • Forever (Java7, Heap space ):

    A concrete implementation of the permanent proxy method area , Store class related information , For the dynamic production class , It is prone to permanent memory overflow .

    To avoid such problems , Put the symbol reference in local memory ; The string constant pool is put in the heap , Static variables are placed on the heap

  • Meta space (Java8, Local memory ).

  • Why use Metaspace to replace permanent generation

    The string has a permanent generation , Prone to performance problems and memory overflows .

    Class and method information is difficult to determine the size , The designation of a permanent agent , Too small is prone to permanent generation overflow , Too big is easy for the old generation to overflow . Dynamic production class loading is easy to occur OOM error . Use Metaspace , Controlled by the actual available space of the system .

    The permanent representative will be GC Bring unnecessary complexity , The recovery efficiency is low ( Loaded classes are not usually unloaded )

  • Is the object really dead

    You need to mark it twice , If not in finalize Method is associated with GCRoots, It will be recycled .( The method is not overwritten or has been called , Deemed unnecessary to perform )( Refer to the data for details )

  • GC ROOT The object contains :

    Objects referenced in the virtual machine stack , The object referenced by the class static property in the method area , Constant reference object in method area , Reference object in local method .

  • strong 、 soft 、 weak 、 Virtual reference

    Note the order of adding to the reference queue . Soft references and soft references , After its object is garbage collected , To join the queue ; Virtual references are added before their objects are recycled .( Specific knowledge inquiry materials )

Garbage collector ( Tricolor )

  • Tricolor notation ( Specific learning needs to be inquired )

    White means that you have not been accessed by the garbage collector , If after the analysis , Still white , Will be recycled

    The black table object has been accessed by the garbage collector , And all references to this object have been scanned . Black object generation The table has been scanned , It's safe to live , If there are other object references pointing to black objects , No need to scan again . Black objects can't be direct ( Without going through the gray object ) Point to a white object .

    gray : Indicates that the object has been accessed by the garbage collector , But at least one reference on this object has not been scanned .

 Insert picture description here

CMS and G1 The garbage collector is running concurrently , There will be misbidding , All of them are operated by three color marking method .

CMS Solution : Write barriers + Incremental updating . Record new references , Black to white .

G1 resolvent : Write barriers +SATB. Record references from gray objects to white objects .

In retag , This part will be rescanned , Prevention of MIS marking .

  • Floating garbage
     Insert picture description here

    After the gray reference is broken , Because it is gray, it will continue to scan , And survive . But it has been associated with GC ROOT No longer connected , So it becomes floating garbage .

    • Pay attention to understanding concurrency and parallelism here .
    • The new generation generally adopts the replication algorithm ( Each garbage collection can be completed at a small cost of object replication , Because every time the new generation collects, a large number of objects die ), Old age objects have a high probability of survival , Generally, the tag sorting algorithm is used .

When does the subject enter the old age

Big object ( Requires a large amount of memory for continuous ) Directly into the elderly generation ( Such as arrays ).( Because the new generation uses replication algorithms to collect garbage , Large objects go directly into the old generation , To avoid the Eden Area and Survivor A large number of memory copies occur in the area )

Space allocation guarantee : When Eden Area and one of them survivor Zone for garbage collection , Put the living object into another survivor Regional time , But there is not enough space , Can only be Survivor Unable to accommodate objects directly into the old age .

Age judgment :1、 The age counter records the age of the object , Once at a time GC Still alive , Age +1, When the set value is exceeded , Directly into the elderly generation .( It's usually 15).2、 Dynamic object age determination , If in Survivor The sum of all object sizes of the same age in the space is greater than Survivor Half of the space , Those whose age is greater than or equal to that age can enter the old age directly , You don't have to wait until you reach the required age .

Space allocation guarantee :

Safe Minor GC: The largest continuous space available in the old generation is larger than that of all objects in the new generation .

Adventurous Minor GC: The maximum continuous space available in the old generation is greater than the average level of promotion to the old age in previous generations and allows guarantee failure ; If less than the average , Go straight ahead Full GC, Make room for the elderly

Safe points and safe areas

https://www.cnblogs.com/newAndHui/p/12246015.html

Escape analysis

https://cloud.tencent.com/developer/article/1761785

https://blog.csdn.net/chengqiuming/article/details/118639672

Parent delegation model

  • reason 、 Written by myself Java.lang.String Will it be loaded

    http://fengziji.com/blog/10

  • How to break the parental delegation model ?

    Because the process of his parents' appointment is loadClass Method , So you want to destroy this mechanism , Then customize a classloader inheritance ClassLoader, Rewrite one of loadClass() Method , Make it not to be assigned by parents .

    Using the thread context class loader .(JDBC The source code of is , Data to be consulted )

    reason :JVM Specify a type of loader to load A Class found A Yes B(A a=new B( )), Then it has to load first B.

    Driver Class is the boot class loader , Implementation classes should also be loaded for the boot class loader , But the implementation class is implemented by the manufacturer , In the user directory , Cannot be loaded by startup class ( Only in their own scope \lib Internal search , So he couldn't find this kind of ), Therefore, an upper and lower file class loader is defined , The default is application class loader .

  • Custom class loaders

    Inherit Class Loader, And rewrite findClass() Method .

How to do GC tuning

  • Optimization objectives

    Minimize the number of objects entering the old age

    Reduce Full GC Execution time of

    Optimize JVM Parameters : Like the stack , Set the mode of the garbage collector .

  • Optimization strategy

    Reserve new objects for the new generation , because Full GC The cost is much higher than Minor GC, Therefore, the objects shall be allocated to the new generation as much as possible , The actual project is based on GC Log analysis of new generation space size allocation is reasonable , Appropriate adoption “-Xmn” Command to adjust the size of the new generation , Minimize the situation that new objects enter the old age directly .

    Big target into the old generation , Although in most cases , It makes sense to assign objects to the next generation , But for large objects, this approach is debatable , If large objects are allocated in the Cenozoic for the first time, there may be insufficient space , As a result, many young objects are assigned to the old age to destroy the object structure of the new generation , There may be frequent Full GC, Therefore, for large objects, you can directly enter the elderly generation .-XX :PretenureSizeThreshold You can set the object size directly into the old age . In addition, the replication of large objects back and forth in the Cenozoic era is also the reason for directly entering the old age .( The old generation is too young ,Full GC Time is short , But maybe out of memory error; Old age makes old age ,FullGC Transmission frequency reduction , but Full GC Time goes up ).

    Reasonably set the age of the elderly ,-XX:MaXTenuringThreshold Set the age of the object entering the old age , Reduce memory usage in old age full gc Frequency of occurrence .

    Set a stable heap size , The heap size setting has two parameters :-Xms Initialize heap size ,-Xmx Maximum heap size .

    If the following indicators are met , In general, there is no need for GC Optimize :
    MinorGC Execution time is less than 50ms;Minor GC Infrequent execution , about 10 Seconds at a time ;
    Full GC Execution time is less than 1s;Full GC Execution frequency is not frequent , No less than 10 minute 1 Time

The squalid

  • Memory leak : Long life objects hold short life objects

  • JVM Tool use ( For example, use oneortwo )

    jstack: Deadlock detection , Dead cycle

    https://blog.csdn.net/sinat_36246371/article/details/53066585

    jstat: Used to collect HotSpot All aspects of virtual machine operation data .

    https://www.cnblogs.com/zhi-leaf/p/10629776.html

  • Why stop the world

    Because the reachability analysis algorithm must be performed in a memory snapshot to ensure consistency . If the object reference relationship is still changing in the process of analysis , The accuracy of the analysis results cannot be guaranteed .

原网站

版权声明
本文为[Autumn rain——]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202211344482520.html